Why is my flex element not centered?

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

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

Can anyone help me understand why it is 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> 
+5
source share
2 answers

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

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

Since your container is flex flex-direction: column :

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

justify-content: center 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 is a more detailed explanation:

+4
source

You need to add alignment elements to .flex-container

 align-items: center; 

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

0
source

Source: https://habr.com/ru/post/1260250/


All Articles