How to Center a Flex Container but Left-Align Flex Items
To center a flex container and left-align flex items, apply display: flex; justify-content: center;
to the flex container, providing it with width
or max-width
. The default behavior of the items will be left-aligned. In case of multi-line flex container, use align-items: flex-start;
or apply align-self: flex-start;
to the individual items:
In your HTML file:
This helps ensure your container is centered while allowing items to maintain left alignment.
Balancing Act: Centering & Left-Aligning
Ever tried walking straight with a tray of glasses? The flex container is much like that tray. align-items: flex-start;
ensures all glasses (items) stay at the start (left-aligned), even when the tray walks in a straight line (centered).
The Great Wrap: Fixing Multi-Row Layouts
For left-aligned items at the start of each row in multi-line layouts, turning flex-wrap
to wrap
and align-content
to flex-start
brings the cavalry in:
This keeps each row packed neatly at the top, making your web page ready for any cat-walk!
It's Media Query Time!
Responsiveness is the backbone of modern web-design. Use display: inline-block;
and media queries to tame flex items like a cowboy tames a wild horse:
Last-row Showdown
On the last row, flex items can rebel. To ensure they toe the line (left align), use your secret CSS weapon: :nth-last-child
. Shh... Don't let them know.
Classroom-Grid Layout
Going beyond flexbox, we have the 2D grid layout system of CSS: display: grid
. With it, arranging the classroom of items is a cinch:
And for the items:
Desandro Masonry: Busting the Grid
Got different-sized items? Desandro Masonry, a JavaScript grid layout library, fits the bill. You might want to try it out if you love the Pinterest layout.
The Practical Magic: Demo and Edge Cases
Practical examples talk better than lorem-ipsum. Include a jsfiddle or live demo link. Remember to look at your layout with squinted eyes to spot the issues. Look for edge cases like single-line items, odd elements in a row, and irregular sized items.
Was this article helpful?