CSS Flexbox Layout for Beginners
CSS Flexbox is a layout method for arranging items in a row or column. It is useful for navigation bars, button groups and aligning content.
Make a flex container
Apply display: flex to the parent element. Its direct children become flex items.
.toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
Choose the main axis
Flexbox lays items out in a row by default. Set flex-direction: column to stack them vertically. The main axis follows this direction, while the cross axis runs perpendicular to it.
.menu {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
Align and wrap items
Use justify-content to distribute items along the main axis and align-items to align them across the cross axis. Add flex-wrap: wrap when items should move onto another line on a narrow screen.
Control how flex items grow or shrink
The flex shorthand sets how an item grows, shrinks, and starts sizing within the row or column. For example, flex: 1 1 12rem gives an item a starting basis of 12rem and allows it to grow or shrink as space changes.
.toolbar-item {
flex: 1 1 12rem;
}
Items grow to use available space when their grow factor allows it. If a row becomes too tight, items can shrink; enable flex-wrap: wrap on the container when they should move to another line instead.
Understand the alignment axes
justify-content works along the main axis, which follows flex-direction. align-items works across the cross axis. If you change from a row to a column, the axes change direction too.
Flexbox questions
How do I center items in a flex container?
Set justify-content: center and align-items: center when you want to center items on both axes. Give the container enough size for the cross-axis alignment to be visible.
When should I use Flexbox instead of Grid?
Flexbox is a natural fit for arranging a group along one axis, such as a toolbar row. Grid is often easier when the layout needs coordinated rows and columns.