DEV Community

Cover image for How to Center A Div With Flexbox
Davide Cannerozzi
Davide Cannerozzi

Posted on

How to Center A Div With Flexbox

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>
Enter fullscreen mode Exit fullscreen mode

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;
}

Enter fullscreen mode Exit fullscreen mode

Without giving any css property to the wrapper container, the flex items will display one below the other.

flexitems

But if we give the property display:flex to the container see what happen. ​

.wrapper{
 display:flex
}
Enter fullscreen mode Exit fullscreen mode

flexcontainer

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
}
Enter fullscreen mode Exit fullscreen mode

flexitemcenter

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
}
Enter fullscreen mode Exit fullscreen mode

flexitemcentervertically

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
}
Enter fullscreen mode Exit fullscreen mode

centerflexbox

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.

Top comments (0)