How to create centered and responsive FlexBox items

How to create centered and responsive FlexBox items

How to create centered and responsive FlexBox items

The Flexbox layout gives you great power when it comes to aligning items horizontally and vertically in a container. If you’ve used float’s before, you know that they only allow items to flow horizontally to  right or to left.

How to center items horizontally in FlexBox

.flexbox-items-container{
  display: flex;
  justify-content: center;
}

Above code will cause the flexbox containerflexbox-items-container items to center horizontally. However when you try to resize the webpage you’ll see that the items don’t wrap to the next line and they will be forced to shrink. This is a normal behavior because the default property of flex-wrap is no-wrap.

How to wrap items in FlexBox

.flexbox-items-container{
 display: flex;
 justify-content: center;
 flex-wrap:wrap;
}

Assigning wrap value to flex-wrap will cause the items to wrap on the next line when there is not enough space for them to fit on one line.

How to center items vertically in FlexBox

.flexbox-items-container{ 
  display: flex; 
  justify-content: center; 
  flex-wrap:wrap;
  align-items: center;
}

Adding property align-items with value center will cause items to center vertically.

 

Be aware that centering elements vertically will not work if the parent of

.flexbox-items-containeror .flexbox-items-container itself does not have a height property specified.

<iframe style="width: 100%; height: 500px; border: 0; border-radius: 4px; overflow: hidden;" src="https://codesandbox.io/embed/w6663434j5?module=%2Fstyles.less" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>

Related Posts