1

I want to vertically center a div (that is in another div) with flexbox.

I tried adding this, but doesn't work:

 display: flex;
 align-items: center;

Here jsfiddle:

https://jsfiddle.net/ms5s5uhy/

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Borja
  • 3,359
  • 7
  • 33
  • 66

1 Answers1

2

You need to put the flex properties in the parent div:

#boss {
    border: 1px solid #000;
    width: 300px;
    height: 300px;
    display: flex;           /* moved here from child div */
    align-items: center;     /* moved here from child div */
}

#kids {
    margin: 0 auto;
    border: 1px solid #000;
    width: 150px;
    height: 150px;
}

Revised Fiddle

OR...

You could remove the align-items keyword property from the flex container and simply use auto margins on the flex item.

#boss {
    border: 1px solid #000;
    width: 300px;
    height: 300px;
    display: flex;           
    /* align-items: center <-- REMOVE */
}

#kids {
    margin: auto;            /* adjusted */
    border: 1px solid #000;
    width: 150px;
    height: 150px;
}

Revised Fiddle

Learn more here: Methods for Aligning Flex Items

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • Another really nice reference can be found here: https://css-tricks.com/snippets/css/a-guide-to-flexbox/ – thutt Aug 03 '17 at 13:55