CSS Flexbox Layout
Flexbox lays out items in a row or column. It solves alignment, equal heights, and spacing problems that were hard with old CSS.
Flexbox Introduction
Flexbox lays out items in a row or column. It solves alignment, equal heights, and spacing problems that were hard with old CSS.
Real-life example: Flexbox is like arranging books on a shelf — you choose row or column, gap between books, and whether they stretch to the same height.
Flex Container Properties
On the parent: display: flex, flex-direction (row/column), justify-content (main axis alignment), align-items (cross axis alignment), gap, and flex-wrap.
Real-life example: justify-content: space-between is like two friends sitting at opposite ends of a bench with empty space between them.
.row {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
gap: 1rem;
flex-wrap: wrap;
}
.column-stack {
display: flex;
flex-direction: column;
gap: 0.75rem;
}Flex Item Properties
On children: flex-grow (share extra space), flex-shrink (shrink if needed), flex-basis (starting size), and align-self (override one item's alignment).
Real-life example: flex: 1 is like saying each child gets an equal share of leftover space on the plate.
.sidebar { flex: 0 0 240px; }
.main { flex: 1 1 auto; }
.push-right {
margin-left: auto;
}
.card-equal {
flex: 1 1 220px;
}Flex Navbar Pattern
A classic Flexbox pattern: logo and links in one row, space-between, wrap on small screens.
Real-life example: Like a shop counter — shop name on the left, menu items spread nicely, order button on the right.
.navbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 1rem 1.25rem;
background: #0f172a;
}
.navbar nav {
display: flex;
gap: 1rem;
flex-wrap: wrap;
}
.navbar a {
color: white;
text-decoration: none;
}Flex Card Row & Center Everything
Use flex-wrap and flex: 1 1 250px for responsive card rows. Use justify-content + align-items center to dead-center content vertically and horizontally.
Real-life example: Centering with Flexbox is like placing a plate exactly in the middle of a table — equal space on all sides.
.card-row {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.card-row .card {
flex: 1 1 250px;
background: white;
border-radius: 12px;
padding: 1.25rem;
box-shadow: 0 4px 12px rgba(15, 23, 42, 0.08);
}
.page-center {
min-height: 70vh;
display: flex;
justify-content: center;
align-items: center;
padding: 1rem;
}