The tags so far—headings, paragraphs, images—each carried a “meaning.” Today’s two, <div> and <span>, are a bit of an odd pair. They have no special meaning of their own; they exist only to “group things together.”
div is a big group
<div> wraps several tags all together and turns them into one group.
<div>
<h2>About the Shop</h2>
<p>We're open from 10 a.m. to 8 p.m.</p>
</div>This <div> changes nothing about the appearance. But it creates a group: “the heading and paragraph, brought together as one ‘shop info block.’” Later, decorations like “make just this block’s background gray” can all be done at once.
span is a pinch within a sentence
<span> is a box for pinching just a part of a sentence. Without breaking the line, it grabs a bit right there on the spot.
<p>The sky today is <span>very blue</span>.</p>This one, too, changes nothing about the look. But when you want to, say, “change the color of just the ‘very blue’ part later,” wrapping it in <span> lets you target it precisely.
Comparing the two
They may look alike, but they behave differently once they wrap something. Let’s line them up.
<div> | <span> | |
|---|---|---|
| What it wraps | groups of tags like headings and paragraphs | a part of a sentence |
| How it handles lines | breaks the line before and after (block) | keeps the line as is (inline) |
| Where to use it | intro blocks, the basis of cards | changing color in a sentence, emphasizing a name |
Pick by asking “is what I want to wrap a group, or a pinch?” and you won’t get lost.
Putting a box inside a box
You can put another <div> inside a <div>. Picture tucking a small box inside a big box.
<div>
<h2>About the Shop</h2>
<div>
<p>We're open from 10 a.m. to 8 p.m.</p>
<p>We're closed on Wednesdays.</p>
</div>
</div>The deeper the nesting gets, the easier it is to mismatch opening and closing tags. If you indent the contents one step at a time, you can see at a glance which </div> closes which <div>.
Summary of this lesson
<div>is a box that groups several tags into a block<span>is a box that pinches just a part of a sentence- Neither carries meaning—they’re “markers for decorating later”