Flexbox
A one-dimensional layout model in CSS for distributing space and aligning items in a row or column.
Detailed Explanation
Flexbox (Flexible Box Layout) revolutionized web design by making it easy to align items, distribute empty space, and handle different screen sizes without using floats or table hacks. It excels at 'inside-out' layouts where the size of the items determines the structure of the container. It is the go-to tool for navigation bars, centered content, and simple grids.
Quick Summary
Flexbox is CSS's one-dimensional layout system. Set display: flex on a parent and its children become flex items that can grow, shrink, wrap, and align along a single axis with concise properties.
Key Takeaways
- Flex containers have a main axis (row or column) and a cross axis perpendicular to it.
- justify-content aligns along the main axis; align-items aligns along the cross axis.
- flex: 1 distributes remaining space among items equally, which is the modern equivalent of width: 100%.
- gap works on flex containers (since 2021 in all browsers) and removes the need for margin hacks.
- min-width: 0 on flex children unlocks proper truncation behaviour for text overflow.
When to use it
- Navigation bars with logo on the left and links on the right.
- Centering arbitrary content vertically and horizontally with three lines of CSS.
- Card rows where items must fill remaining space evenly.
- Form rows where a label has a natural width and the input takes whatever is left.
Common Mistakes
- Reaching for Flexbox when Grid would model the two-dimensional layout more clearly.
- Forgetting min-width: 0 and watching long text break out of a flex container.
- Setting flex: 1 1 0 on every item without realising it forces equal width regardless of content.
- Using row-reverse or column-reverse for visual ordering, it confuses keyboard and screen-reader users.
Flexbox, Frequently Asked
When should I use Flexbox vs Grid?
Flexbox for one-dimensional layouts (a row of cards, a navbar). Grid for two-dimensional layouts (page templates, calendar views). They compose well, Grid for page structure, Flexbox inside each cell.
Does flexbox support wrapping?
Yes, with flex-wrap: wrap. Once enabled, items move to a new line when they would otherwise overflow, and the cross axis becomes multi-line for align-content to control.
Is flexbox accessible?
It is layout, not semantics, so it does not affect accessibility on its own. But reordering items with order or row-reverse changes the visual sequence without changing the DOM sequence, keyboard users still tab in DOM order, which can be confusing.