Overview
Flexbox is the layout model for arranging items in a single row or column. It handles alignment, spacing, and distribution without floats or hacks. This tutorial covers the container and item properties, with practical layout examples.
Enabling Flexbox
.container {
display: flex;
}
All direct children become flex items and are laid out along the main axis.
Container Properties
flex-direction
| Value | Main axis |
|---|---|
row (default) | Left to right |
row-reverse | Right to left |
column | Top to bottom |
column-reverse | Bottom to top |
justify-content (main axis)
| Value | Effect |
|---|---|
flex-start | Packed at the start |
center | Centered |
flex-end | Packed at the end |
space-between | Equal space between items |
space-around | Equal space around each item |
space-evenly | Equal space between and at the edges |
align-items (cross axis)
| Value | Effect |
|---|---|
stretch (default) | Items fill the container height |
flex-start | Aligned to the top |
center | Vertically centered |
flex-end | Aligned to the bottom |
baseline | Aligned by text baseline |
flex-wrap
.container {
flex-wrap: wrap;
}
By default items shrink to fit on one line. wrap allows them to move to the next line.
Item Properties
flex-grow, flex-shrink, flex-basis
.item {
flex: 1 1 200px; /* grow shrink basis */
}
| Property | Meaning |
|---|---|
flex-grow | How much extra space the item takes |
flex-shrink | How much the item shrinks when space is tight |
flex-basis | Initial size before growing or shrinking |
align-self
.item {
align-self: flex-end;
}
Overrides the container's align-items for a single item.
order
.item-featured {
order: -1;
}
Lower values appear first. Useful for moving a featured item to the front without changing the HTML.
Practical Layouts
Perfect Centering
.center {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
Sticky Footer
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main {
flex: 1;
}
Navigation Bar
.nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
}
Card Grid with Wrapping
.cards {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.card {
flex: 1 1 300px;
}
Flexbox vs Grid
| Dimension | Flexbox | Grid |
|---|---|---|
| Layout direction | One-dimensional | Two-dimensional |
| Best for | Rows or columns of items | Full page layouts |
| Sizing | Content-driven | Track-driven |
