14. div and span Tags
Introduction
Section titled “Introduction”The <div> and <span> elements are generic containers used for grouping and styling content. While they don’t have inherent semantic meaning, they’re essential for layout and CSS styling. Modern HTML prefers semantic elements when possible, but div and span remain useful for generic containers.
The div Element
Section titled “The div Element”The <div> element is a block-level container used for grouping content.
<div class="container"> <h1>Title</h1> <p>Content</p></div>Characteristics
Section titled “Characteristics”- Block-level element
- Takes full width
- Starts on new line
- Used for layout and grouping
The span Element
Section titled “The span Element”The <span> element is an inline container used for styling portions of text.
<p>This is <span class="highlight">highlighted</span> text.</p>Characteristics
Section titled “Characteristics”- Inline element
- Only takes necessary width
- Stays on same line
- Used for styling text portions
Common Use Cases
Section titled “Common Use Cases”Layout with div
Section titled “Layout with div”<div class="header">Header content</div><div class="main">Main content</div><div class="footer">Footer content</div>Styling with span
Section titled “Styling with span”<p>Price: <span class="price">$99.99</span></p>Modern Alternative
Section titled “Modern Alternative”Prefer semantic elements when possible:
<!-- Good: Semantic --><header>Header content</header><main>Main content</main><footer>Footer content</footer>
<!-- Also acceptable: div for layout --><div class="grid-container"> <div class="item">Content</div></div>