HTML Div Center
The HTML <div>
element is a generic container for holding other elements. It is commonly used for grouping elements together and styling them. In this article, we will focus on how to center a <div>
element both horizontally and vertically using CSS.
Horizontally Center a Div
To horizontally center a <div>
element in CSS, you can use the margin
property. Set the left and right margins to auto
and the width of the <div>
to a specific value or percentage.
<!DOCTYPE html>
<html>
<head>
<style>
.center {
width: 50%;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="center">
<p>This div is horizontally centered.</p>
</div>
</body>
</html>
Output:
Vertically Center a Div
To vertically center a <div>
element in CSS, you can use the display: flex
and align-items: center
properties. This will vertically center the <div>
within its parent container.
<!DOCTYPE html>
<html>
<head>
<style>
.container {
height: 300px;
display: flex;
align-items: center;
}
</style>
</head>
<body>
<div class="container">
<div>
<p>This div is vertically centered.</p>
</div>
</div>
</body>
</html>
Output:
Horizontally and Vertically Center a Div
To horizontally and vertically center a <div>
element in CSS, you can combine the techniques used above. Set the left and right margins to auto
, the width of the <div>
to a specific value or percentage, and use display: flex
with align-items: center
.
<!DOCTYPE html>
<html>
<head>
<style>
.container {
height: 300px;
display: flex;
justify-content: center;
align-items: center;
}
.center {
width: 50%;
}
</style>
</head>
<body>
<div class="container">
<div class="center">
<p>This div is both horizontally and vertically centered.</p>
</div>
</div>
</body>
</html>
Output:
Center Multiple Divs
You can also center multiple <div>
elements using the same techniques. Just apply the styling to each <div>
that you want to center.
<!DOCTYPE html>
<html>
<head>
<style>
.container {
height: 300px;
display: flex;
justify-content: center;
align-items: center;
}
.center {
width: 50%;
margin: 20px;
}
</style>
</head>
<body>
<div class="container">
<div class="center">
<p>This is div 1.</p>
</div>
<div class="center">
<p>This is div 2.</p>
</div>
<div class="center">
<p>This is div 3.</p>
</div>
</div>
</body>
</html>
Output:
Conclusion
In this article, we have explored how to center <div>
elements in HTML using CSS. By applying the techniques mentioned above, you can easily achieve both horizontal and vertical centering for your <div>
elements. Experiment with different styles and layouts to create visually appealing designs for your webpages.