This chapter explains the <div> and <span> elements in HTML, focusing on their roles as block-level and inline containers. Learn how to use them for structuring and styling content with clear examples.
The <div> element is a block-level container that groups content, such as text, images, or other elements, and takes up the full width of its parent container. It starts on a new line and is commonly used for creating layout sections like headers, footers, or content blocks. Since it’s non-semantic, it relies on CSS for styling.
<div>
<h3>Header Section</h3>
<p>This is a block-level container.</p>
</div>
<div>
<p>Another block-level container below the first one.</p>
</div>
Preview:
The <span> element is an inline container used to style or group small portions of text or elements within a line. Unlike <div>, it doesn’t start a new line and only takes the width of its content. It’s ideal for applying CSS to specific words or phrases.
<p>This is a normal sentence with a <span>highlighted</span> word.</p>
<p>This sentence has another <span>styled</span> word.</p>
Preview:
Block-level elements like <div> occupy the full width of their container and start on a new line, making them ideal for structuring layouts. Inline elements like <span> only take the width of their content and stay within the text flow, perfect for styling specific parts of content.
<div>This div takes the full width and starts on a new line.</div>
<p>This paragraph has an <span>inline</span> element that stays in the flow.</p>
Preview:
Create a layout with <div> and style text using <span>.
<div class="container">
<h3>My Section</h3>
<p>This is a <span>cool</span> example of block and inline elements.</p>
</div>
Preview:
Understanding <div> as a block-level element and <span> as an inline element helps you structure and style HTML content effectively. Practice to master their use!