Home »
CSS
How to vertically center a div element for all browsers using CSS?
In this tutorial, we will learn how to vertically center a div element for all browsers using CSS with the help of examples?
By Shahnail Khan Last updated : July 12, 2023
As we all know, the <div> tag is used as a container for elements in HTML. Any type of content can be put inside the div tag. We first add elements and style them with CSS. We can center the div elements both horizontally and vertically. In this tutorial, we will only know how to vertically center a div element using CSS?
Vertically center a div element for all browsers using CSS
Well, this can be easily done by using CSS Flexbox properties.
The introduction of Flexbox in CSS made web developers' life easier. It shortens your line of code and consumes less time.
We use only one flex property, i.e., the align-items property. Set this property value to "center". You can specify the height of the div container. Then, we have to set the height of the body and HTML to 100%.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vertically center a div element</title>
</head>
<style>
body,
html {
height: 100%;
}
.main2 {
display: flex;
align-items: center;
height: 40%;
}
.main1,
.main2 {
border: 4px solid red;
background-color: #fff018;
}
</style>
<body>
<h1> The div elements are not vertically centered</h1>
<div class="main1">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR2Us0ygule9jbbygOVLYuCDjLr2cJE95uccg&usqp=CAU"
alt="IncluHelp">
<h2>Lorem ipsum dolor sit.</h2>
</div>
<h1> The div elements are vertically centered </h1>
<div class="main2">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR2Us0ygule9jbbygOVLYuCDjLr2cJE95uccg&usqp=CAU"
alt="IncluHelp">
<h2>Lorem ipsum dolor sit.</h2>
</div>
</div>
</body>
</html>
Output
As you can see, in the first box, we haven't applied CSS Flexbox properties to center a div element. In the second box, both the elements (text & image) are vertically centered.
CSS Examples »