Categories
CSS

How to center horizontally and vertically with CSS Flexbox?

Spread the love

Sometimes, we want to center horizontally and vertically with CSS Flexbox.

In this article, we’ll look at how to center horizontally and vertically with CSS Flexbox.

How to center horizontally and vertically with CSS Flexbox?

To center horizontally and vertically with CSS Flexbox, we set flex-direction to column to make the main axis vertical.

Then we set justify-content to center to center the items vertically and set align-items to center to center them horizontally.

To do this, we write

<div id="container">
  <div class="box" id="bluebox">
    <p>DIV #1</p>
  </div>

  <div class="box" id="redbox">
    <p>DIV #2</p>
  </div>
</div>

to add some nested divs.

Then we write

#container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.box {
  width: 300px;
  margin: 5px;
  text-align: center;
}

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

Then we align the child divs to be centered vertically and horizontally with

flex-direction: column;
justify-content: center;
align-items: center;

We set the height so that flex-direction: column will be applied.

Conclusion

To center horizontally and vertically with CSS Flexbox, we set flex-direction to column to make the main axis vertical.

Then we set justify-content to center to center the items vertically and set align-items to center to center them horizontally.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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