What is the Difference Between <div> and <span>?
Answer
Both <div> and <span> are generic container elements with no semantic meaning, but they differ in their display behavior.
Key Differences
| Feature | <div> | <span> |
|---|---|---|
| Display | Block | Inline |
| Width | Full container width | Content width only |
| Line break | Before and after | None |
| Can contain | Any elements | Inline elements only |
| Common use | Layout sections | Styling text portions |
Example
<!-- div takes full width, creates new lines -->
<div style="background: lightblue;">Block 1</div>
<div style="background: lightgreen;">Block 2</div>
<!-- span stays inline -->
<p>
This is <span style="color: red;">red text</span> and
<span style="color: blue;">blue text</span> inline.
</p>
Visual Result
┌─────────────────────────────┐
│ Block 1 (lightblue) │ ← div (full width)
├─────────────────────────────┤
│ Block 2 (lightgreen) │ ← div (full width)
└─────────────────────────────┘
This is [red text] and [blue text] inline. ← spans (inline)
When to Use
- Use
<div>for grouping elements for layout or styling sections - Use
<span>for styling small portions of text or inline content - Prefer semantic elements (
<section>,<article>) over<div>when possible