Flexbox arranges items along one main axis. It is best for navigation bars, toolbars, media objects, button groups, and rows or columns where items should share space.
.nav-list {
display: flex;
gap: 1rem;
align-items: center;
}
Main axis and cross axis
The main axis comes from flex-direction:
.row {
display: flex;
flex-direction: row;
}
.column {
display: flex;
flex-direction: column;
}
In a row, the main axis is inline. In a column, the main axis is block.
justify-content aligns along the main axis:
.toolbar {
display: flex;
justify-content: space-between;
}
align-items aligns along the cross axis:
.toolbar {
align-items: center;
}
Gap
Use gap for spacing between flex items:
.actions {
display: flex;
gap: 0.75rem;
}
This is cleaner than putting margins on every button.
Wrapping
Flex items try to fit on one line unless wrapping is enabled:
.tag-list {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
This is useful for tags, chips, and action rows that can flow onto another line.
Flex sizing
Flex sizing has three parts:
.sidebar {
flex: 0 0 16rem;
}
.content {
flex: 1 1 0;
}
The shorthand is:
flex: grow shrink basis
flex-grow: can the item take extra space?flex-shrink: can the item shrink?flex-basis: what size does it start from?
For equal-width flexible items:
.pricing-card {
flex: 1 1 18rem;
}
Each card wants at least 18rem, can grow, and can shrink when needed.
A practical media object
<article class="media-card">
<img src="/images/course.jpg" alt="" />
<div>
<h2>CSS layout</h2>
<p>Build responsive rows, grids, and components.</p>
</div>
</article>
.media-card {
display: flex;
gap: 1rem;
align-items: start;
}
.media-card img {
inline-size: 6rem;
aspect-ratio: 1;
object-fit: cover;
border-radius: 0.5rem;
}
Flexbox makes the image and text sit side by side while preserving content size.
Normal flow
Items keep document order. Spacing changes margins between blocks.
Preview
Generated CSS
When flexbox is not enough
Flexbox is one-dimensional. It can wrap, but each line is laid out independently. If you need rows and columns to line up together, use grid.
What to carry forward
- flexbox lays out items along one main axis
flex-directionsets the main axisjustify-contentworks on the main axisalign-itemsworks on the cross axisgapis the normal spacing toolflex: grow shrink basiscontrols how items share space- use grid when rows and columns both matter
Quick Check
One answerWhich layout tool is usually best for a toolbar where items sit in one row and share space?
Choose the best answer and use it to track your progress through the lesson.
Why that answer is correct
Flexbox is designed for one-dimensional layout: a row or column of related items.
The next lesson introduces grid for two-dimensional layout.