Vertical centering is a process to center an HTML element vertically. We need to set parent div position as relative position and child div as absolute position.
<style>
/*Container Div */
.parent{
background-color:black;
height:300px;
width:300px;
position:relative
}
/*Child Div */
.child{
background-color:red;
height:50px;
width:50px;
position:absolute;
margin:0;
top:50%;
-ms-transform:translateY(-50%);
transform:translateY(-50%);
}
</style>
Now create a container div with a class name parent and a child div with class name child and apply the above CSS properties.
<head>
<style>
.parent{background-color:black;
height:300px;
width:300px;
position:relative}
.child{background-color:red;
height:50px;
width:50px;
position:absolute;
margin:0;
top:50%;
-ms-transform:translateY(-50%);
transform:translateY(-50%);
}
</style>
</head>
<body>
<div class="parent">
<div class="child">Child Element</div>
</div>
</body>
We can also use the CSS flex property to Vertically center an HTML element.
<style>
/*Container Div */
.parent{
background-color:black;
height:300px;
display:flex;
align-items:center;
}
/*Child Div */
.child{
background-color:red;
height:50px;
width:50px;
}
</style>
It is very simple to use the flex property to vertically center an HTML element. We just need to create a container div with a class name parent and a child div with class name child and apply the above CSS properties.
<head>
<style>
/*Container Div */
.parent{
background-color:black;
height:300px;
display:flex;
align-items:center;}
/*Child Div */
.child{
background-color:red;
height:50px;
width:50px;}
</style>
</head>
<body>
<div class="parent">
<div class="child">Child Element</div>
</div>
</body>
We can use the CSS flex property to Vertically and Horizontally center an HTML element.
<style>
/*Container Div */
.parent{
background-color:black;
height:300px;
display:flex;
justify-content: center;
align-items:center;
}
/*Child Div */
.child{
background-color:red;
height:50px;
width:50px;
}
</style>
<head>
<style>
/*Container Div */
.parent{
background-color:black;
height:300px;
display:flex;
justify-content: center;
align-items:center;}
/*Child Div */
.child{
background-color:red;
height:50px;
width:50px;}
</style>
</head>
<body>
<div class="parent">
<div class="child">Child Element</div>
</div>
</body>