HTML <div> Element
The <div> element is a container used to group other HTML elements. It is a block element, so it starts on a new line and takes full width.
1. Basic Usage
You can use <div> to group elements like paragraphs or headings.
<div> <h2>Hello</h2> <p>This is inside a div.</p> </div>
Hello
This is inside a div.
2. Styling a Div
You can use CSS to style divs with background color, padding, borders, etc.
<div style="background-color:orange; padding:15px; border-radius:8px"> Styled Div Example </div>
Styled Div Example
3. Multiple Divs
You can use multiple divs to organize your page layout.
<div style="background-color:#0ea5e9; color:white; padding:10px">Header</div> <div style="background-color:#f97316; color:white; padding:10px">Content</div> <div style="background-color:#10b981; color:white; padding:10px">Footer</div>
Header
Content
Footer
4. Div with Class or ID
Using class and id attributes allows you to target specific divs with CSS or JavaScript. Here’s how they differ:
- class: Can be used on multiple divs, ideal for styling groups of elements.
- id: Must be unique on the page, ideal for selecting a single specific div.
Example: Using a Class
<div class="highlight"> This div has a class. </div> <div class="highlight"> Another div with the same class. </div>
This div has a class.
Another div with the same class.
Example: Using an ID
IDs are unique, so you can style or select a single div:
<div id="main-container"> This div has an ID. </div>
This div has an ID.
Styling with CSS
You can target a class or ID in your CSS like this:
.highlight {
background-color: #fbbf24;
color: black;
padding: 10px;
border-radius: 6px;
}
#main-container {
background-color: #3b82f6;
color: white;
padding: 15px;
border-radius: 6px;
}
Next Lesson → HTML <span> Element
Previous Lesson → HTML Block and Inline Elements