Centering flexbox items
Flexbox makes the common “centre this in both directions” problem pleasantly small. Put the layout rules on the parent:
.parent {
display: flex;
justify-content: center;
align-items: center;
}
justify-content centres the items along the main axis. With the default flex-direction: row, that means horizontally. align-items centres them along the cross axis, which is vertical in this case.
That axis detail matters. If you change the container to flex-direction: column, the directions swap even though the property names stay the same.
If you only need horizontal centring, keep justify-content: center. If you only need vertical centring, keep align-items: center. And remember that both properties belong on the flex container, not the child you are trying to centre.
Enjoyed reading this?
If you found this article helpful, consider supporting my writing. Every little bit helps keep this blog going.
Related articles
- Making Links Easy to Recognize
Make links recognisable with underlines, clear focus states, useful text, and behaviour that does not surprise the reader.
- When CSS Layout Order Stops Matching the HTML
Keep Grid and Flexbox layouts aligned with the HTML order so keyboard focus and screen reader reading do not jump around the page.
- Keyboard Focus Styles With :focus-visible
Keep a clear keyboard focus indicator while avoiding the same focus ring after every pointer interaction.