HTML <div> Tag
To group together a section of HTML elements, the HTML <div> tag is used. It acts as a container to encapsulate other elements. An HTML document is thus divided into sections, using the HTML <div> tag. CSS styles can also be applied to many elements at once using the HTML <div> tag.
Example 1:
<!DOCTYPE html> <html> <body> <p>Hye!!</p> <div style="width:500px; background-color:crimson; color:white; border:5px solid yellow; text-align:center;"> <h1>Hello World!!</h1> <p>HAVE A GREAT DAY.</p> </div> <p>Bye Bye!!</p> </body> </html>
Explanation:
In the above example, we have used the HTML <div> element to apply the CSS style properties only to a certain group of elements of an HTML document.
Example 2: Creating a layout of a website using the HTML <div> tag.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<style>
.header{
padding: 20px;
background-color:crimson;
text-align: center;
}
.header h3{
color:white;
font-size: 20px;
}
.nav{
background-color:gray;
padding: 5px;
}
.nav li{
list-style: none;
display: inline-block;
padding: 8px;
}
.nav a{
color: white;
}
.nav ul li a:hover{
text-decoration: none;
color: blue;
}
.lside{
float: left;
width: 50
min-height: 200px;
background-color: pink;
text-align: center;
}
.rside
{
text-align: center;
float: right;
width: 50
min-height: 200px;
background-color: white;
}
.footer{
background-color:#455e64;
text-align: center;
padding: 10px;
}
.footer p{
color: white;
}
</style>
</head>
<body>
<div>
<div class="header">
<h3>LAYOUT EXAMPLE</h3>
</div>
<!-- Nav -->
<div class="nav">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Contact Us</a></li>
<li style="float: right;"><a href="#">SIGN-IN</a></li>
<li style="float: right;"><a href="#">SIGN-UP</a></li>
</ul>
</div>
<!-- main -->
<div style="height:200px">
<div class="lside">
<h2>HELLO WORLD!!</h2>
</div>
<!-- side -->
<div class="rside">
<h3>How are you today?</h3>
</div>
</div>
<!-- footer -->
<div class="footer">
<p><strong>©Copyright w3schools.com</strong></p>
</div>
</div>
</body>
</html>
Explanation:
In the above example, we are creating a website layout using the HTML <div> tag. Different CSS style properties are also applied to the elements of the different <div> sections as per the specified “class” names for each <div> section.
Difference between HTML <div> tag and HTML <span> tag:
| HTML <div> Tag | HTML <span> Tag |
| Block element. | Inline element. |
| Wraps large sections of elements. | Wraps small portion of texts, images, etc. |
Tag specific Attributes:
| Attribute | Value | Uses | |
| align | left
right center justify |
Used to specify the content-alignment inside a <div> element. | Not supported in HTML5. |
Global Attributes:
The HTML Global attributes are supported by the HTML <div> tag.
Event Attributes:
The HTML Event attributes are supported by the HTML <div> tag.
Supporting Browsers:
Chrome, IE, Firefox, Opera, and Safari.