HomeGuideLabGlossary

Center flex items

The Solution at a Glance

  1. Set the alignment properties and to center on the flex container.
  2. Size the flex container to be bigger than the flex items. If they’re the same size, the flex items won’t seem centered.
  3. If you allow flex items to wrap into multiple flex lines with : wrap, make sure to center the flex lines in the flex container with : center.

Set the alignment properties to center

The flex container lays out flex items in the main direction set by . Set : center on the flex container to center the flex items along this direction.

justify-content: center123Main direction

Flex items align themselves in the cross direction in their flex line with align-self. By default align-self is auto, which means each flex item will use the value set on the flex container. This lets you align all flex items at once. Set : center on the flex container.

align-items: centeralign-self: auto?123Crossdirection

Sizing the flex container

The flex container is sized using the layout type chosen by the parent of the flex container. The parent might just be continuing the default Flow layout type, or it might itself start a new Flex or Grid layout.

.flex-container.flex-containerbodybodydisplay: blockdisplay: grid

Depending on this layout type, the flex container might be sized based on the size of its flex items.

If that’s the case, then there won’t be any extra space for the flex items to be centered in.

13justify-content: centerblock-size: autoflex-direction: columnMaindirection2

So you need to figure out a way to make the flex container the desired size, and that will depend on the layout type that the flex container participates in. For example, you could set an explicit fixed size on the flex container.

132block-size: 280px

Multi-line flex container

Instead of having all flex items on a single flex line, you can allow them to wrap into multiple flex lines with : wrap.

1233Nope,can’t fitBetter!flex-wrap: wrap

By default, the flex lines will stretch to fill the flex container in the cross direction if there’s any space left. Instead, you want to make sure those flex lines are centered in the flex container.

123align-content: normal(normal behaves like stretch)

You set the alignment and distribution of flex lines in the cross direction of the flex container with the property. Center the flex lines in the cross direction with : center.

123align-content: center