How to vertically center a div element for all browsers using CSS?

Spread the love

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 center a div element for all browsers using CSS?

To vertically center a div element for all browsers using CSS, we can use flexbox.

For instance, we write

<div class="container">
  <div>Div to be aligned vertically</div>
</div>

to add a div inside a div.

Then we write

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: green;
}

body,
html {
  height: 100%;
}

to make the outer div a flex container with display: flex;.

Then we add align-items: center; and justify-content: center; to vertically and horizontally center the items in the outer div respectively.

Conclusion

To vertically center a div element for all browsers using CSS, we can use flexbox.

Leave a Reply

Your email address will not be published. Required fields are marked *