Sometimes, we want to center horizontally and vertically with CSS Flexbox.
We’ll look at how to center horizontally and vertically with CSS Flexbox, in this article.
How to center horizontally and vertically with CSS Flexbox?
We set flex-direction
to column
to center horizontally and vertically with CSS flexbox , 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
We set flex-direction
to column
to make the main axis vertical, to center horizontally and vertically with CSS flexbox.
Then we set justify-content
to center
to center the items vertically and set align-items
to center
to center them horizontally.