CSS Flexbox Cheat Sheet
Flexbox lays items out in one direction, in a row or a column. Turn it on with display: flex on the parent.
Container properties
| Property | Common values | What it does |
|---|---|---|
flex-direction | row, column, row-reverse | Sets the main axis |
flex-wrap | nowrap, wrap | Lets items move to a new line |
justify-content | flex-start, center, space-between, space-around, space-evenly | Spaces items along the main axis |
align-items | stretch, center, flex-start, flex-end, baseline | Aligns items on the cross axis |
align-content | same as justify-content | Spaces wrapped lines |
gap | 1rem | Space between items |
Item properties
| Property | What it does |
|---|---|
flex-grow | How much extra space the item takes, as a share |
flex-shrink | How easily it shrinks when space is short |
flex-basis | Its starting size before growing or shrinking |
flex: 1 | Shorthand to share space equally |
align-self | Overrides align-items for one item |
order | Changes the visual order |
Patterns
Centre anything
.parent { display: flex; justify-content: center; align-items: center; }
Navbar with the logo left and links right
.nav { display: flex; align-items: center; gap: 1rem; }
.nav .logo { margin-right: auto; }
Equal columns that wrap
.cards { display: flex; flex-wrap: wrap; gap: 1rem; }
.cards > * { flex: 1 1 16rem; }
Tips
justify-contentfollows the main axis, so in a column it moves items vertically.- An item that refuses to shrink may need
min-width: 0. - Use Grid when you need rows and columns at the same time.