22. <div> vs <span> (Generic Containers)
The 2 most widely used boxes for CSS styling and layout
Real-life analogy
Div is a big empty carton box that can be filled with many things, and Span is a small transparent plastic bag that fits in the middle of a line!
Explanation
These two are used when you don't have any specific semantic tag:
<div>(Division): The most prominent block-level container. It is used to build sections, cards and grid layouts of a web page.<span>: The most prominent inline container. It is used to change the colour or style of just 1 or 2 words inside a paragraph.
Golden rules
- Use div only when necessary; if possible, use meaningful tags (header, main, section).
Common mistake
Filling the whole page with nothing but 100 divs (Div Soup).
Example code
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; padding: 20px;">
<!-- div: block container -->
<div style="background: #f8fafc; border: 1px solid #cbd5e1; padding: 12px; border-radius: 8px;">
<h4 style="margin: 0 0 6px 0;">This is inside the div</h4>
<p style="margin: 0; font-size: 13px;">
In this sentence <span style="color: #dc2626; font-weight: bold;">only this word is red</span> (via <span>).
</p>
</div>
</body>
</html>
Quick quiz
Which tag is most suitable for changing the colour of just one word in the middle of a paragraph?
- <div>
- <p>
- <span>
- <section>
Show answer
Answer: <span>
<span> is an inline tag that lets you apply styling without breaking the flow of the sentence.