json1 json1 - 9 days ago 5
CSS Question

Why isn't my flex item aligning in the center?

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>




Answer

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:

Comments