The HTML <div> Element
The <div> element is a generic container for other HTML elements and is a block-level element.
Grouping Content with <div>
The <div> element has no required attributes, but style and class are common. When used together with CSS, the <div> element can be used to style blocks of content.
Example 1: Styling with a Class
In this example, we use CSS to style two <div> elements with the same class.
html
<!DOCTYPE html>
<html>
<head>
<style>
.city {
background-color: tomato;
color: white;
border: 2px solid black;
margin: 20px;
padding: 20px;
}
</style>
</head>
<body>
<div class="city">
<h2>London</h2>
<p>London is the capital of England.</p>
</div>
<div class="city">
<h2>Paris</h2>
<p>Paris is the capital of France.</p>
</div>
</body>
</html>Example 2: Basic Grouping
A <div> element simply acts as a container for other elements.
html
<div>
<p>This is a paragraph inside a div.</p>
<p>This is another paragraph in the same div.</p>
</div>In the first example, we have two <div> elements. Both are styled with the "city" class, which groups them visually with a background color, padding, and a border.
Test Yourself with an Exercise
Is the <div> element a block-level or an inline element?