Vertical centering is a method using which we can align the center to a child element of an HTML container element.
CSS Vertical Centering
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. Now try to run this code by clicking on the Try it yourself button.
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>
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. Now try to run this code by clicking on the Try it yourself button.
<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><divclass="parent"><divclass="child">Child Element</div></div></body>