Intermediate · CSS layout and responsive design · topic 24 of 64 · 30 min
Flexbox
Explanation
Parent and children
Flexbox works on two levels. The parent with display: flex is the flex container. Its direct children are flex items, and they line up in a row by default.
Two axes
The main axis is the direction items flow: left to right for a row, top to bottom for a column. The cross axis runs across it. justify-content arranges items along the main axis; align-items aligns them along the cross axis.
.navbar {
display: flex;
flex-direction: row; /* default; column stacks them */
justify-content: space-between; /* main axis */
align-items: center; /* cross axis */
gap: 16px; /* space between items */
}| justify-content | Result |
|---|---|
| flex-start | Items packed at the start |
| center | Items in the middle |
| space-between | First and last at the edges, equal space between |
| space-around / space-evenly | Space around every item |
Wrapping
By default items stay on one line and shrink. flex-wrap: wrap lets them move to the next line when there is no room, which is useful for tags, filter chips or a row of cards on a phone.
Growing and shrinking
.search-bar { display: flex; gap: 8px; }
.search-bar input { flex: 1; } /* take all the free space */
.search-bar button { flex: none; } /* keep its natural size */flex is a shorthand for three values: flex-grow (how much to grow), flex-shrink (how much to shrink) and flex-basis (the starting size). flex: 1 is the most common setting.
Perfect centring
.center-me {
display: flex;
justify-content: center;
align-items: center;
min-height: 100dvh;
}Watch the lesson
Flexbox · 1/6
Flexbox lines items up in one direction, a row or a column.
Prefer a video by a teacher? Find free videos on “css flexbox tutorial for beginners” on YouTube ↗
In real life: A food delivery app header
The top bar of a food app shows the location on the left, a search box that fills the middle and a profile icon on the right. One display: flex with align-items: center, gap: 12px and flex: 1 on the search box does the whole layout, and it still fits on a small phone.
Practice (0/2 done)
Make the .nav a flex container with justify-content: space-between, align-items: center and a gap of 16px.
Build a search bar: .search is a flex container with gap 8px, the input inside it has flex: 1 so it fills the space, and the button keeps its size.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.