3

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?

lw1.at
  • 1,528
  • 11
  • 25
  • 1
    Or you could just use `100vh` https://jsfiddle.net/z8m6n6pz/1/ – Nenad Vracar Feb 21 '16 at 11:52
  • 3
    Why does the second not work? Because the height has to be 100% of *something* and you haven't told it what to be 100% of. – Paulie_D Feb 21 '16 at 11:56
  • 1
    the HTML and BODY tags have `auto` height by default, meaning the height is based on the content. when you give them `height:100%` they will fill the entire height of the viewport. Alternatively, as suggested by @NenadVracar you can just use the viewport units instead. (be careful of browser support tho) – Aziz Feb 21 '16 at 11:59
  • Open DevTools (F12) and inspect element and it's height. Div #login_container is centered, it's just that the parent element height is too small for it to be seen. – noviewpoint Feb 21 '16 at 12:05
  • Thanks, now I understand. I missed that the body has no height unless there is some content. Sorry if this was a silly first question. – lw1.at Feb 21 '16 at 12:10
  • 1
    http://stackoverflow.com/a/31728799/3597276 – Michael Benjamin Feb 21 '16 at 12:20

1 Answers1

4

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).

Madan Bhandari
  • 2,094
  • 2
  • 26
  • 46