div and span
Prerequisites: Articles, sections, and asides
div and span are generic containers with no meaning at all.
divis a block container — it starts on a new line and takes the full width available.spanis an inline container — it sits inside a line of text.
<div class="card">
<h2>Rye Loaf</h2>
<p>Price: <span class="price">£4.20</span></p>
</div>
They exist so you can group things for CSS (styling, layout) or
JavaScript. The class attribute gives them a name to target.
Block and inline
Browsers display most elements in one of two ways by default:
| Block (new line, full width) | Inline (flows in text) |
|---|---|
div, p, h1–h6, ul, ol, li, table, form, header, section, article |
span, a, strong, em, code, img, abbr, time |
CSS can change any element's display, so this describes the default look,
not what an element may contain. HTML's own content rules say, for
example, that a p can only contain text-level (phrasing) content — not
a div or a heading.
Divitis
A page built only from divs works visually but tells assistive technology nothing:
<!-- Avoid: meaningless markup -->
<div class="header">
<div class="nav">
<div class="link" onclick="location.href='/'">Home</div>
</div>
</div>
The fake "link" can't be reached with the Tab key, isn't announced as a link, and can't be opened in a new tab. The fix is simply the right elements:
<header>
<nav aria-label="Main">
<a href="/">Home</a>
</nav>
</header>
Rule: first look for an element that means what you want. Use div
and span only when nothing else fits — and then they're perfectly
fine.
Practice
A designer wants the word "Sale" inside a paragraph to be red, and wants three product cards wrapped in a single box for a grid layout. Which elements would you use?
Show solution
A span for "Sale" (it's inline and has no special meaning — unless
it's important, then strong), and a div around the cards (a pure
layout wrapper). Each card itself could be an article, or the cards
could be lis in a ul.
<p>Everything is on <span class="sale">Sale</span> this week.</p>
<div class="grid">
<article><h2>Rye</h2></article>
<article><h2>Spelt</h2></article>
<article><h2>Sourdough</h2></article>
</div>