Lesson 12: Div & Span Elements
What are Div and Span?
<div> and <span> are generic container elements used to group content for styling or scripting purposes.
Key Differences:
- <div> - Block-level element (takes full width, starts new line)
- <span> - Inline element (only takes needed width, stays in line)
The <div> Element
A block-level container used to group sections of content.
HTML Code:
<div style="background-color: lightblue; padding: 10px;">
<h3>Title</h3>
<p>Content inside div</p>
</div>
The <span> Element
An inline container used to style part of text or inline content.
HTML Code:
<p>This is <span style="color: red;">important</span> text.</p>
Block vs Inline
| Feature |
<div> (Block) |
<span> (Inline) |
| Display |
Takes full width |
Takes only needed width |
| Line Break |
Starts on new line |
Stays in line |
| Width/Height |
Can set width & height |
Cannot set width & height |
| Use Case |
Layout sections |
Styling inline text |
Using Div for Layout
<div class="container">
<div class="header">Header</div>
<div class="content">Main Content</div>
<div class="footer">Footer</div>
</div>
Using Span for Styling
HTML Code:
<p>
Price: <span class="price">$99</span>
</p>
<p>
Call <span class="phone">555-1234</span>
</p>
Classes and IDs
Div and span are often used with class or id attributes for CSS styling:
<div id="header" class="blue-bg">Header</div>
<div class="card">Card 1</div>
<div class="card">Card 2</div>
Nested Divs
<div class="outer">
<div class="inner">
<p>Nested content</p>
</div>
</div>
💡 Best Practices:
- Use semantic HTML when possible (<header>, <nav>, etc.)
- Use <div> when no semantic tag fits
- Use <span> only for inline styling
- Give meaningful class names
- Don't overuse - avoid "div soup"
When to Use What
Use Semantic Tags:
- <header>, <footer>, <nav>, <article>, <section>
Use <div> for:
- Generic containers without semantic meaning
- Layout wrappers
- Grouping for styling
Use <span> for:
- Styling part of text
- Inline elements that need styling
Practice Exercise
Try This:
Create a product card using divs and spans:
- Outer <div> as container
- Inner divs for image, title, description
- <span> for price with colored styling
- <span> for "Sale" badge