·7 min read
CSS Flexbox Guide
Flexbox is the modern way to layout elements in one dimension (row or column). This guide covers every property with visual examples.
Flex Container Properties
.container {
display: flex;
/* Direction */
flex-direction: row; /* row | row-reverse | column | column-reverse */
/* Wrapping */
flex-wrap: nowrap; /* nowrap | wrap | wrap-reverse */
/* Main axis alignment */
justify-content: flex-start; /* flex-start | flex-end | center | space-between | space-around | space-evenly */
/* Cross axis alignment */
align-items: stretch; /* stretch | flex-start | flex-end | center | baseline */
/* Multi-line alignment */
align-content: flex-start; /* flex-start | flex-end | center | space-between | space-around | stretch */
gap: 16px; /* spacing between items */
}Flex Item Properties
.item {
flex-grow: 0; /* how much to grow relative to siblings */
flex-shrink: 1; /* how much to shrink relative to siblings */
flex-basis: auto; /* initial size before grow/shrink */
/* Shorthand */
flex: 0 1 auto; /* grow shrink basis */
flex: 1; /* equal sizing */
/* Individual alignment */
align-self: center; /* override container align-items */
order: 0; /* visual order (lower = first) */
}Common Patterns
Center a single element
.center {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}Space items evenly
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
}Equal width columns
.columns {
display: flex;
gap: 16px;
}
.columns > * { flex: 1; }Card with footer at bottom
.card {
display: flex;
flex-direction: column;
}
.card-footer { margin-top: auto; }Responsive wrap
.grid {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.grid > * {
flex: 1 1 300px; /* min 300px, grow to fill */
}Flexbox vs Grid
- Flexbox — one-dimensional (row OR column)
- Grid — two-dimensional (rows AND columns)
- Use Flexbox for navbars, card layouts, centering
- Use Grid for page layouts, complex grids, dashboards
Cheat Sheet
justify-content— main axis (horizontal for row)align-items— cross axis (vertical for row)flex: 1— equal sizinggap— spacing between itemsflex-wrap: wrap— items wrap to next line