How to Use CSS Flexbox: A Practical Guide
CSS Flexbox is a one-dimensional layout system that makes aligning, distributing, and reordering elements simple. Before Flexbox, centering a div was a running joke in web development. With Flexbox, it's one line. This guide covers the practical patterns you'll use every day.
- Learn CSS Flexbox with practical examples.
- Covers flexbox basics.
- Covers centering anything.
- Covers distributing space.
- Covers direction and wrapping.
Flexbox Basics
Flexbox works on two roles: the flex container (parent) and flex items (children). Add display: flex to the parent, and its direct children become flex items arranged in a row by default:
.container {
display: flex;
}
That single line changes everything โ children line up horizontally, stretch to equal height, and can be aligned, distributed, and reordered with simple properties.
Centering Anything
The most common Flexbox pattern โ centering both horizontally and vertically:
gap instead of margin hacks for flexbox spacing. It keeps layout code cleaner and is supported in all modern browsers..center-everything {
display: flex;
justify-content: center;
align-items: center;
}
justify-content controls the main axis (horizontal by default). align-items controls the cross axis (vertical by default). Center both, and the child sits in the exact middle of the container. This works for single elements, groups of elements, and even full-page layouts.
Distributing Space
justify-content controls how free space is distributed between items: flex-start (default, items packed to the start), flex-end (packed to the end), center (centered), space-between (equal space between items, no space at edges), space-around (equal space around each item), space-evenly (equal space between and at edges). space-between is the most common for navigation bars and card grids. space-evenly is cleaner when you want equal spacing everywhere.
width, height, top, or left. These trigger layout recalculations on every frame and can drop performance below 60fps.Direction and Wrapping
flex-direction changes the main axis: row (default, horizontal), row-reverse, column (vertical), column-reverse. flex-wrap controls whether items wrap to new lines when they don't fit: nowrap (default, items shrink), wrap (items wrap to next line). For responsive grids, combine flex-wrap: wrap with a min-width on items:
.grid { display: flex; flex-wrap: wrap; gap: 16px; }
.grid > * { flex: 1 1 300px; }
This creates a grid where items are at least 300px wide and wrap to new rows as needed.
The flex Shorthand
The flex property on items controls how they grow, shrink, and their base size: flex: 1 means 'grow to fill available space equally.' flex: 0 0 auto means 'don't grow, don't shrink, use natural size.' flex: 2 on one item and flex: 1 on others means the first item gets twice as much space. The Flexbox Playground lets you experiment with all these properties visually and see the CSS output in real time.