Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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>
like image 519
json1 Avatar asked Nov 24 '16 01:11

json1


1 Answers

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:

  • In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?
like image 190
Michael Benjamin Avatar answered Oct 11 '22 09:10

Michael Benjamin