CSS Flexbox, or the Flexible Box Layout, is a one-dimensional layout method for arranging items in rows or columns. It allows items to expand to fill extra space or shrink to fit into smaller containers. Marketers and designers use it to create responsive interfaces that look consistent across different screen sizes.
What is CSS Flexbox?
Flexbox is a layout mode designed for complex applications and web pages. While traditional CSS layouts used four different algorithms (block, inline, table, and positioned), Flexbox introduces a more flexible model. It gives you control over the direction, alignment, and size of elements even when their dimensions are unknown.
The W3C published specific updates to improve this model, including the 19 November 2018 Candidate Recommendation, which addressed web compatibility and refined how browsers calculate intrinsic sizes.
Why CSS Flexbox matters
Flexbox solves alignment problems that were historically difficult for web developers.
- Vertical centering: You can center a block of content inside its parent container with one or two lines of code.
- Equal height columns: Columns in a layout will adopt the same height automatically, even if they contains different amounts of content.
- Space distribution: You can make children of a container take up equal width or height regardless of the total space available.
- Responsive layouts: Items can "flex" to adapt to the user's screen, reducing the risk of broken layouts on mobile devices.
- Visual reordering: You can change the visual order of elements without changing the underlying HTML code.
How CSS Flexbox works
The system relies on a parent element, the flex container, and its immediate children, called flex items. When you apply display: flex to a container, it establishes a new formatting context.
The two axes
Everything in Flexbox refers to two axes:
- Main Axis: The primary direction items are laid out. If
flex-directionisrow, the axis is horizontal. If it iscolumn, the axis is vertical. - Cross Axis: The direction perpendicular to the main axis.
Layout calculations are based on these axes rather than fixed directions like left, right, top, or bottom. This allows Flexbox to support all writing modes, including right-to-left languages like Arabic.
Key alignment properties
- justify-content: Aligns items along the main axis. Values include
flex-start,flex-end,center,space-between, andspace-around. - align-items: Aligns items along the cross axis for the entire container.
- align-self: Overrides the
align-itemsvalue for a single specific item. - flex-wrap: Controls whether items stay on one line or wrap onto multiple rows or columns.
Best practices
- Use shorthand properties: Use the
flexshorthand instead of individualflex-grow,flex-shrink, andflex-basisproperties. This ensures unspecified components are reset correctly to accommodate common use cases. - Preserve source order: Only use the
orderproperty for visual adjustments. Keep the logical order of the HTML source correct to ensure accessibility for screen readers and keyboard users. - Avoid percentage margins: Different browsers may resolve percentage margins or paddings differently in Flexbox. Use fixed units or auto margins to maintain consistency.
- Choose flex-flow for brevity: Combine
flex-directionandflex-wrapinto theflex-flowshorthand to keep your stylesheets clean.
Common mistakes
Mistake: Applying flex properties to the wrong element.
Fix: Remember that justify-content and align-items go on the parent container, while flex or order go on the individual child items.
Mistake: Changing the order property and expecting tabbing order to follow.
Fix: The tabbing order always follows the code order. If you move a link visually to the top, a keyboard user will still reach it in its original HTML position.
Mistake: Using Flexbox for two-dimensional grid layouts.
Fix: Flexbox is one-dimensional. While it can wrap items, it cannot control both rows and columns at the same time. Use CSS Grid for 2D layouts.
Mistake: Expecting vertical-align to work on flex items.
Fix: The vertical-align property has no effect in a Flexbox context. Use align-items or align-self instead.
Examples
Navigation bar alignment
You can create a navigation bar where links are on the left and a "Login" button is on the right. By setting display: flex on the container and margin-left: auto on the Login button, the button will push itself to the far end of the available space.
Modern catalog layout
For a product catalog, you can ensure all items in a row have the same height. Even if one product has a short description and another has a long one, Flexbox stretches all item boxes to match the tallest one in the row.
CSS Flexbox vs traditional layout modes
| Feature | Flex Layout | Block Layout | Table Layout |
|---|---|---|---|
| Primary Goal | Apps and complex pages | Documents | 2D Tabular data |
| Centering | Easy vertical/horizontal | Difficult vertical | Simple vertical |
| Responsiveness | Items shrink/grow | Requires more math | Inflexible |
| Floats | Ignored | Standard | Not applicable |
FAQ
When should I use display: inline-flex instead of display: flex?
Use display: flex to create a block-level container that takes up the full width of its parent. Use display: inline-flex if you want the container itself to behave like an inline element, only taking up as much width as its items require.
Does Flexbox help with SEO?
Flexbox does not directly affect search rankings, but it significantly improves user experience and page speed. Because it handles responsiveness efficiently, it helps your site pass Core Web Vitals related to layout stability and mobile-friendliness.
Can I nest flex containers?
Yes. You can make an element a flex item and a flex container at the same time. This is common when you have a main row of items and need to align content vertically inside one of those items.
How do flex-grow and flex-shrink work?
flex-grow is a number that tells an item how much of the "free space" it should take. flex-shrink tells the item how much to contract when the container is too small. These are proportions, so an item with flex-grow: 2 will take double the available space compared to an item with flex-grow: 1.
What is flex-basis?
flex-basis defines the default size of an element before the remaining space is distributed. It is often set to auto, which looks at the item's width or height property. If those are also auto, it uses the item's content size.