Davide Cannerozzi
Posted on February 7, 2022
Before Flexbox, centering elements in CSS was a little bit frustrating.
WHAT IS FLEXBOX?
Flexbox is a CSS3 layout model that allows developers to build one dimension layout.
First of all, you need to have:
a flex container (.wrapper)
flex items (.flex-item)
<body>
<div class=”wrapper”>
<div class=”flex-item”></div>
<div class=”flex-item”></div>
<div class=”flex-item”></div>
</div>
</body>
I will give some style to the flex items, to show them on the web page.
.flex-item{
border:1px solid red;
height:30px;
width:30px;
}
Without giving any css property to the wrapper container, the flex items will display one below the other.
But if we give the property display:flex to the container see what happen.
.wrapper{
display:flex
}
The Flex Items are now displayed horizontally but not centered.
How To Center Horizontally
Now that we have our flex-container, we can learn how to center the flex-items horizontally.
The only thing to do is set the justify-content:center
props to the flex-container.
The justify-content property allows us to position the flex-item along the main-axis of the flex-container.
As you can see, the divs are now centered horizontally inside the container.
.wrapper{
display:flex;
justify-content:center
}
How To Center Vertically
Instead of the justify-content property, you have to use the align-items:center
property.
This property allow us to position the flex-items along the cross-axis.
You are probably notice that the flex item didn’t move from the initial position.
Why?
To center an element vertically, we should give a height to the flex container.
Let’s make the container 100vh which means 100% of the viewport height.
Now the divs are centered vertically.
Well Done!
.wrapper{
display:flex;
height:100vh;
align-items:center
}
How To Center Vertically And Horizontally .
Since we already know how to center vertically and horizontally, you can easily guess how to do it.
We need to use both align-content and justify-content property.
Remember: set a height to the container; otherwise, it will not work.
.wrapper{
display:flex;
height:100vh;
justify-content:center;
align-items:center
}
Flexbox is a powerful tool that every front-end developer should master.
As you can see from caniuse.com, it is very well supported by all modern browsers.
Posted on February 7, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.