Vertical centering is a method using which we can align the center to a child element of an HTML container element.
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>
<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;
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>