HTML Div

What is the Div Element?

The <div> element is a generic container for flow content. It has no inherent semantic meaning and is used to group elements for styling purposes or to create page structure. The <div> element is a block-level element that can contain other block-level and inline elements.

Basic Div Element

The <div> element is used as a container:

Example
<div>
    <h2>Section Title</h2>
    <p>This is content inside a div element.</p>
    <p>You can put multiple elements inside a div.</p>
</div>

Div with Styling

Divs are commonly used with CSS classes or inline styles for styling:

Example
<style>
    .container {
        background-color: #f0f0f0;
        padding: 20px;
        border: 2px solid #4b3190;
        margin: 20px 0;
    }
    .box {
        background-color: #fdbb30;
        padding: 15px;
        margin: 10px;
        border-radius: 5px;
    }
</style>
<div class="container">
    <h2>Container Div</h2>
    <div class="box">Box 1</div>
    <div class="box">Box 2</div>
</div>

Div for Layout

Divs are commonly used to create page layouts:

Example
<style>
    .header { background-color: #4b3190; color: white; padding: 20px; text-align: center; }
    .sidebar { background-color: #f2f2f2; padding: 15px; width: 200px; float: left; }
    .content { margin-left: 220px; padding: 15px; }
    .footer { background-color: #333; color: white; padding: 10px; text-align: center; clear: both; }
</style>
<div class="header">Header</div>
<div class="sidebar">Sidebar</div>
<div class="content">Main Content</div>
<div class="footer">Footer</div>

Nested Divs

Divs can be nested inside other divs:

Example
<style>
    .outer {
        background-color: lightblue;
        padding: 20px;
        margin: 20px;
    }
    .inner {
        background-color: lightgreen;
        padding: 15px;
        margin: 10px;
    }
</style>
<div class="outer">
    <p>Outer div</p>
    <div class="inner">
        <p>Inner div</p>
        <div class="inner">
            <p>Nested inner div</p>
        </div>
    </div>
</div>

Div vs Semantic Elements

While <div> is still useful, HTML5 introduced semantic elements that provide meaning:

Example - Using Div (Generic)
<div class="header">Header content</div>
<div class="nav">Navigation</div>
<div class="main">Main content</div>
<div class="footer">Footer content</div>
Example - Using Semantic Elements (Recommended)
<header>Header content</header>
<nav>Navigation</nav>
<main>Main content</main>
<footer>Footer content</footer>

When to Use Div

Use <div> when:

When Not to Use Div

Prefer semantic HTML5 elements when appropriate:

Best Practices