CSS Flexbox in Practice
Codevity Admin · 10/24/2026
Codevity Admin · 10/24/2026
Flexbox is a one-dimensional layout system: it lays items out along a row or a column and gives you simple control over spacing and alignment. You turn it on with one line:
.toolbar {
display: flex;
}The direct children of .toolbar are now flex items.
Everything in Flexbox depends on the main axis and the cross axis. By default the main axis runs horizontally (flex-direction: row) and the cross axis vertically. Set flex-direction: column and they swap.
| Property | Controls | Common values |
|---|---|---|
justify-content | alignment along the main axis | flex-start, center, space-between, space-around |
align-items | alignment along the cross axis | stretch (default), center, flex-start, flex-end |
gap | space between items | 1rem, 8px |
flex-wrap | whether items wrap onto new lines | nowrap (default), wrap |
A navigation bar with the logo on the left and links on the right:
.nav {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
}Centering something both ways:
.hero {
display: flex;
justify-content: center;
align-items: center;
min-height: 60vh;
}A sticky footer, where the footer sits at the bottom even on short pages:
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main {
flex: 1; /* take all the spare vertical space */
}Each item has three sizing properties, usually written with the flex shorthand:
flex-grow: how much of the leftover space this item takes. 0 means none.flex-shrink: how willing the item is to shrink when space is short. 1 is the default.flex-basis: the starting size before growing or shrinking..sidebar { flex: 0 0 240px; } /* fixed 240px, never grows or shrinks */
.content { flex: 1; } /* fills the rest */flex: 1 is shorthand for flex: 1 1 0%, which makes sibling items share the space equally.
.tags {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}Items stay on one line until they run out of room, then wrap naturally.
min-width: 0 to the item.align-items: center seems to do nothing. The container needs extra height to center in, so give it a height or min-height.flex-direction: column, justify-content is the vertical one.margin for gaps. gap is simpler and does not leave a stray margin on the last item.Use Flexbox when you are arranging items in a single line or column and want the content to decide the sizes. Use CSS Grid when you need rows and columns to line up, such as a card gallery or a full page layout. They combine well: a grid for the page, flexbox inside each component.