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:

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>

Output:

Title

Content inside 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>

Output:

This is important text.

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>

Output:

Price: $99

Call 555-1234

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:

When to Use What

Use Semantic Tags: Use <div> for: Use <span> for:

Practice Exercise

Try This:

Create a product card using divs and spans: