🌱BeginnerSemantic HTML

Div and Span

Use <div> and <span> as generic containers when no semantic element fits.

Overview

<div> and <span> are the generic, non-semantic containers of HTML. They carry no inherent meaning they exist purely to group elements for styling or scripting purposes. <div> is a block-level element it starts on a new line and fills its container's width. Use it to group block-level elements. <span> is an inline element it flows within text. Use it to wrap parts of text for styling or JavaScript hooks. Always prefer a semantic element if one fits your content. Use <div>/<span> only when no semantic element is appropriate.

Key Points

  • •<div>: generic block container no semantic meaning, used for layout and grouping
  • •<span>: generic inline container wraps text for styling or JS targeting
  • •Both are meaningless to screen readers prefer semantic elements when possible
  • •class and id attributes are what give <div> and <span> their purpose in practice
  • •Over-using <div> (also called "divitis") makes code hard to read and less accessible
  • •When choosing: if a semantic element fits, use it; otherwise use div/span

Examples

div for layout grouping

<!-- Card component no specific semantic element for "card" -->
<div class="card">
  <div class="card-image">
    <img src="product.jpg" alt="Product">
  </div>
  <div class="card-body">
    <h3>Product Name</h3>
    <p>$29.99</p>
    <button>Add to Cart</button>
  </div>
</div>

div is appropriate here because "card" is a UI pattern, not a semantic content type.

span for inline text targeting

<p>
  The temperature today is
  <span class="temperature" id="temp">72°F</span> a perfect day for a walk.
</p>

<!-- JavaScript can update the span's content -->
<script>
  document.getElementById('temp').textContent = '75°F';
</script>

Semantic vs div comparison

<!-- SEMANTIC: use these when the role is clear -->
<header>...</header>
<nav>...</nav>
<main>...</main>
<article>...</article>
<footer>...</footer>

<!-- DIV: use when no semantic element fits -->
<div class="modal-overlay">
  <div class="modal">
    <div class="modal-header">...</div>
  </div>
</div>

Common Mistakes

  • Using <div> instead of semantic elements like <article>, <section>, <header>
  • Nesting too many divs each one should have a clear purpose via class or id
  • Using <span> to change font size or color when CSS on the parent is cleaner

Note

Before writing a <div>, ask: "Is there a semantic HTML element for this?" Check: header, footer, nav, main, aside, article, section, figure, address, time. If none fit, then div is the right choice.

Exercises

Write HTML to solve each exercise. Use Preview to see it render in a live iframe, then mark as done.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

What semantic meaning does <div> carry?