Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical center div with flexbox

Tags:

css

flexbox

I tried vertically centering a div with flexbox: Oddly align-items: center didn't change anything. After playing around for some time I realized that I need to set body and html to height:100%;.

HTML:

<div id="login_container">
    <div class="login"></div>
    <div class="login"></div>
    <div class="login"></div>
</div>

CSS:

#login_container {
    display: flex;
    align-items: center;
    justify-content: center;
    height:100%;
}
.login {
    background-color: #008000;
    width: 100px;
    height: 100px;
    margin: 2px;
}

For comparison: This fiddle is working while this one isn't.

Why do I have to add

body,html {
    height:100%;
}

so that the div is vertically aligned? Am I missing something?

like image 956
lw1.at Avatar asked Mar 24 '26 22:03

lw1.at


1 Answers

Default value of height is auto, this means your html/body will not be full screen.

To get full screen content you have specify height to 100% or 100vh.

so that the div is vertically aligned? Am I missing something?

Yes, your content is vertically centred of parent (in this case vertically center to content of html/body). You have just missed to set height of html/body to 100% (full screen).

like image 179
Madan Bhandari Avatar answered Mar 26 '26 12:03

Madan Bhandari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!