Flexbox (CSS Flexible Box Layout) is a one-dimensional layout model ideal for arranging items in a row or column. It’s been supported in all major browsers since 2015 and is the go-to tool for navigation bars, card rows, centred hero sections, and any component where you need items to align, distribute space, and wrap responsively.
Problem: How do you align items, distribute space, and build one-dimensional layouts in CSS without using floats or inline-block workarounds?
Solution: Use CSS Flexbox — apply display: flex to a container and control the main axis with justify-content, the cross axis with align-items, and wrapping behaviour with flex-wrap.
Core concepts on the container:
.nav-menu {
display: flex;
flex-direction: row; /* default — items go left to right */
flex-wrap: wrap; /* allow wrapping to the next line */
justify-content: space-between; /* space along the main axis */
align-items: center; /* align along the cross axis */
gap: 1rem; /* space between items (modern browsers) */
}
/* Column layout */
.sidebar {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
Controlling individual items:
.card {
flex: 1 1 280px; /* grow, shrink, basis */
/* flex: 1 means "grow to fill available space equally" */
}
.card--featured {
flex: 2; /* takes twice as much space as a regular card */
}
/* Push a specific item to the far end */
.nav-menu .nav-menu__cta {
margin-left: auto;
}
/* Vertical centering inside a container of fixed height */
.hero {
display: flex;
align-items: center; /* vertical */
justify-content: center; /* horizontal */
min-height: 60vh;
}
A real-world responsive card grid using Flexbox:
.posts-grid {
display: flex;
flex-wrap: wrap;
gap: 1.5rem;
}
.posts-grid .post-card {
flex: 1 1 calc( 33.333% - 1rem );
min-width: 260px;
}
@media ( max-width: 640px ) {
.posts-grid .post-card {
flex: 1 1 100%;
}
}
NOTE: Use CSS Grid when you need two-dimensional control over both rows and columns simultaneously. Flexbox is the right choice for single-axis layouts — navbars, button groups, card rows — where items should flow and wrap naturally.