HomeGuideLabGlossary

Center flex container, left-align flex items

The Solution at a Glance

Keep the flex items aligned to the main-start side of the flex container

Flex items are aligned to the side where the main direction of the flex container starts. That’s the inline-start side for flex containers with : row and the block-start side for flex containers with : column.

Main directionflex-direction: rowMain directionflex-direction: column

The flex container aligns its flex items in the main direction with . The initial value of is flex-start, which refers to side where the main direction starts as we saw above. This is what we want, so we don’t make any changes to .

123Main direction starts herejustify-content: flex-start

Center the flex container’s content box

The flex items are laid out inside the content box of the flex container. If the flex container’s content box extends to the edges of the viewport, that’s where the flex items will get laid out. So we need to change where the flex container’s content box is—that’s what we will be centering.

How we center the flex container will depend on the type of layout picked by the parent box of the flex container. That’s because in CSS parent boxes pick the layout type for its children, just like our flex container box decided that its children would be flex items.

main.flex-containerbody#one#two#threedisplay: griddisplay: blockdisplay: flex

For example, you could have the parent of the flex container become a flex container itself, and have the parent center it using alignment properties.

main.flex-containerbodydisplay: flexjustify-content: center

Or, the parent of the flex container could choose the Grid layout type to lay out the flex container. Whatever it is, we need to make sure the flex container itself is centered to get our desired effect.

main.flex-containerbodydisplay: gridplace-content: center

Alternatively, you could try pushing the contents of the flex container toward the center by setting a padding on the flex container. This is a bit tricky, because we may not know exactly how much padding we should set on the flex container.

123padding: 48px