How to use margin: auto to vertically-align a div with CSS?

Spread the love

Sometimes, we want to use margin: auto to vertically-align a div with CSS.

In this article, we’ll look at how to use margin: auto to vertically-align a div with CSS.

How to use margin: auto to vertically-align a div with CSS?

To use margin: auto to vertically-align a div with CSS, we use flexbox.

For instance, we write

<div id="parent">
  <div id="child">hello world</div>
</div>

to add nested divs.

Then we write

#parent {
  width: 50vw;
  height: 50vh;
  background-color: gray;
  display: flex;
}

#child {
  margin: auto auto;
}

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

And then we vertically center align the child div with margin: auto auto;.

Conclusion

To use margin: auto to vertically-align a div with CSS, we use flexbox.

Leave a Reply

Your email address will not be published.