Sometimes, we want to vertically center a div element for all browsers using CSS.
In this article, we’ll look at how to vertically center a div element for all browsers using CSS.
How to vertically align an image inside a div with CSS?
To vertically center a div element for all browsers using CSS, we use flexbox.
For instance, we write
<div class="parent">
<img class="child" src="https://picsum.photos/300/300" />
</div>
to add a div with an img element inside.
Then we write
.parent {
align-items: center;
background: red;
display: flex;
height: 250px;
width: 250px;
}
to make the div a flex container with display: flex;
.
Then we vertically center the img element with align-items: center;
.
Conclusion
To vertically center a div element for all browsers using CSS, we use flexbox.