Center flex items
The Solution at a Glance
- Set the alignment properties
and
to
center
on the flex container. - Size the flex container to be bigger than the flex items. If they’re the same size, the flex items won’t seem centered.
- 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.
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.
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.
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.
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.
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
.
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.
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
.