The <div>
and <span>
tags are used for grouping and styling content in HTML. While <div>
is a block-level element, <span>
is an inline element. They’re often paired with CSS to control the layout and appearance of content.
HTML Div and Span Tags Syntax
Div Tag:
<div>
: This tag defines a division or section in an HTML document. It is a block-level element that starts on a new line and occupies the full width of its container. It is typically used to group larger sections of content.
<div>This is a div element.</div>
Span Tag:
<span>
: This tag is an inline element that groups inline elements and text. It does not start on a new line and only takes up as much width as necessary. It is often used to apply styles to specific parts of text.
<span>This is a span element.</span>
HTML Div and Span Tags Example Code
Explanation of Code:
- Div Tag (
<div>
): The<div>
element is used to group larger sections of content. It is a block-level element, meaning it creates a new line and occupies the full width of its container. In this example, the<div>
tag creates a box around its contents, allowing for styling through CSS. - Span Tag (
<span>
): The<span>
element is used for inline grouping, allowing developers to apply styles or target specific pieces of text without affecting the flow of other elements. In the example, the<span>
tag highlights a specific part of the text within a paragraph, demonstrating how it can be styled differently from surrounding content.
<!DOCTYPE html> <html> <head> <title>Div and Span Tags Example</title> <style> .box { background-color: lightcoral; padding: 20px; margin: 10px 0; } .highlight { background-color: yellow; } </style> </head> <body> <h1>Understanding Div and Span Tags</h1> <div class="box"> <h2>This is a Div Element</h2> <p>The <strong><div></strong> tag is a block-level element that groups together larger sections of content.</p> </div> <p>This is a regular paragraph, but <span class="highlight">this part is highlighted using a span element</span>.</p> <div class="box"> <h2>Using Span for Inline Formatting</h2> <p>Here is an example of <span class="highlight">inline text</span> that can be styled differently from the surrounding text.</p> </div> </body> </html>