How to Center a Div in Flexbox
There are many ways to center things in CSS, but CSS Flexbox is one of the simplest. CSS Flexbox is a layout model that aids in the alignment of one-directional items. In this short post, we’ll look at how to center items both horizontally and vertically.
To center the Div element
- We use the property of display set to flex – display: flex;
- Align items to center using – align-items: center;
- The last step is to set justify-content to center – justify-content: center;
Main Axis and Cross Axis
- All flex boxes have a direction, in this case it’s horizontal starting from the left side to the right
- The main axis goes from left to right
- The cross axis is top to bottom
To center our box we use the align-items
property to align our item on the cross axis, which in this case is the block axis running vertically. We use justify-content
to align the item on the main axis, which in this case is the inline axis running horizontally.
It is also important to add a height to the container of your div. For example height: 100vh
. vh
unit stands for viewport height. Specifying 100vh is equivalent to occupying 100% of entire visible screen height.
Code
<div class="box">
<div></div>
</div>
.box {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
.box div {
width: 200px;
height: 200px;
border: 2px solid #0b2535;
border-radius: 5px;
background-color: #e2ecee;
}
output
Conclusion
The properties we have covered in this guide are as follows:
- display: flex – This defines a flex container; inline or block depending on the given value. It enables a flex context for all its direct children.
- align-items – controls alignment of all items on the cross axis.
- justify-content – controls alignment of all items on the main axis.
See also
How do you use Cascading Style Sheets (CSS)?
What are the 4 properties in a CSS Box Model?
What are CSS Rules and Selectors?
If you liked this article, then please share. You can also find me on Twitter for more updates.
Top comments (1)
Nice!
It's worth mentioning that if we have only one flex-item we want to center, like in the example, we can just use
margin:auto
in that item, to center on "flex-item level". Of course, then we wouldn't usealign-items: center; justify-content: center;
in the container because we don't center on "flex-container level"!