Skip to content

14. div and span Tags

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 is a block-level container used for grouping content.

<div class="container">
<h1>Title</h1>
<p>Content</p>
</div>
  • Block-level element
  • Takes full width
  • Starts on new line
  • Used for layout and grouping

The <span> element is an inline container used for styling portions of text.

<p>This is <span class="highlight">highlighted</span> text.</p>
  • Inline element
  • Only takes necessary width
  • Stays on same line
  • Used for styling text portions
<div class="header">Header content</div>
<div class="main">Main content</div>
<div class="footer">Footer content</div>
<p>Price: <span class="price">$99.99</span></p>

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>