4: Containers: div, span & When to Care

These are the two most boring tags, but they run the internet. They're just boxes, but one stacks vertically, and one flows with text.

Block vs. inline: you can see it in HTML alone

div = block (takes full width, stacks)

div one
div two — next line, full width

span = inline (flows with text, only as wide as content)

This is a paragraph with span one and span two inline. They don't break lines.

<div>block: new line, full width</div>
<div>another block</div>

<p>text <span>inline</span> more text <span>inline</span></p>
Why it matters: CSS display (Module 08) can change this, but the default matters for no-CSS readability and for which CSS properties work (width does nothing on inline. You'll see why inline "feels broken" in Module 08).

div vs. span vs. semantic alternatives

TagDefaultUse when…
<div>blockGrouping for layout / styling, no better semantic tag
<span>inlineWrapping a few words for style (color, highlight)
<section>, <article>, <nav>blockContent has meaning. Prefer over div
<!-- prefer semantic -->
<section>...</section>   <!-- not <div class="section"> -->

<!-- div is fine for layout wrappers -->
<div class="card-grid">
  <article class="card">...</article>
  <article class="card">...</article>
</div>

<!-- span for inline styling -->
<p>Price: <span class="price">$12</span></p>

id vs. class vs. data-*

AttrUnique?UseExample
idmust be unique per pageAnchor targets, JS hooks, one-off<section id="pricing">
classreusableStyling (CSS), grouping<div class="card featured">
data-*anyCustom data for JS, no styling<button data-count="3">
<div id="hero">: one hero per page
<div class="card">: many cards
<div data-state="open">: JS reads this
Gotcha: id must not repeat. Duplicate id="foo" makes #foo links and getElementById unpredictable. Use class for repeated things.

Nesting rules & validation

<!-- broken: p can't contain div -->
<p>Hello <div>oops</div> world</p>
<!-- browser renders as: <p>Hello </p><div>oops</div> world -->

<!-- correct -->
<div><p>Hello</p><div>card</div><p>world</p></div>

validator.w3.org catches nesting errors. Paste your HTML, fix the red lines.


Live demo: refactor this div soup

Before (div soup)
<div id="header">
  <div class="nav">
    <div>Home</div>
  </div>
</div>
<div class="main">
  <div class="post">
    <div class="title">Hi</div>
    <div>body...</div>
  </div>
</div>
After (semantic)
<header>
  <nav>
    <a>Home</a>
  </nav>
</header>
<main>
  <article>
    <h2>Hi</h2>
    <p>body...</p>
  </article>
</main>
Exercise: Refactor:

Take your Module 3 recipe/resume page and:

  1. Replace div soup with semantic tags where possible.
  2. Use class for repeated cards/items, id only for anchor targets.
  3. Wrap inline highlights in <span> (e.g., prices, labels).
  4. Validate for zero errors.
Prev3: Lists & Semantic Next5: Your First CSS Rule