Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center divs in body horizontally and vertically with flexbox

Tags:

html

css

flexbox

I am trying to center some divs vertically and horizontally using flexbox but it's not working as expected.
here is an image illustrating what am having and what I expect.

enter image description here

And here is the code:

<html lang="en">

<body>

<style type="text/css">

    body{
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }
</style>

    <div>111111</div>
    <div>222222</div>
    <div>333333</div>

</body>

</html>

EDIT

Of course, I know it'd be better puting the divs in a container and that's what I tried first but in that case, I end up with something like this:

enter image description here

So as you can see, the divs are get centred in the container as expected but the container itself is not.

like image 549
Asme Just Avatar asked Dec 05 '22 20:12

Asme Just


1 Answers

Your code is fine, you should only add a min-height: 100vh to the body so the div can be centered in the viewport height (the body doesn't always cover the viewport height, it just takes minimal space to contain its children)

Example: http://codepen.io/anon/pen/xGQpKO

like image 172
Fabrizio Calderan Avatar answered May 25 '23 11:05

Fabrizio Calderan