5

I am trying to center a red box in the middle of the page.

I have set the flex container to 100% in height, and have also set the html,body to 100%, and it still does not align center.

Can anyone please help me understand why its not working? Thanks!

html, body {
  height: 100%;
}
.flex-container {
  display: flex;
  flex-flow: column;
  justify-content: center;
  height: 100%;
}
.box {
  flex: 0 0 100px;
  background: red;
  width: 100px;
}
<div class='flex-container'>
    <div class='box'></div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
json1
  • 93
  • 4

2 Answers2

5

You use justify-content to align flex items on the main axis.

You use align-items to align flex items on the cross axis.

Since your flex container is flex-direction: column:

  • the main axis is vertical, and
  • the cross axis is horizontal.

justify-content: center is working fine.

You just need to add align-items: center.

html, body {
  height: 100%;
}
.flex-container {
  display: flex;
  flex-flow: column;
  justify-content: center;       /* centers flex items vertically, in this case */
  align-items: center; /* NEW */ /* centers flex items horizontally, in this case */
  height: 100%
}
.box {
  flex: 0 0 100px;
  background: red;
  width: 100px;
}
<div class='flex-container'>
  <div class='box'></div>
</div>

Here's a more detailed explanation:

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
0

You need to add align-items to .flex-container

align-items: center;

See here for an example https://jsfiddle.net/x9gyheo6/1/

Blezx
  • 614
  • 2
  • 6
  • 19