CSS
Flexbox
Flexbox (Flexible Box Layout) is a one-dimensional layout system — it arranges items in a row or a column. It makes aligning items and distributing space straightforward.
/* ── Apply to the CONTAINER ─────────────────── */
.container {
display: flex;
/* Direction: row (default) | column | row-reverse | column-reverse */
flex-direction: row;
/* Main axis alignment (horizontal when row) */
justify-content: space-between;
/* flex-start | flex-end | center | space-between | space-around | space-evenly */
/* Cross axis alignment (vertical when row) */
align-items: center;
/* flex-start | flex-end | center | stretch | baseline */
/* Wrap items when they don't fit */
flex-wrap: wrap;
/* Space between items */
gap: 16px;
}
/* ── Apply to FLEX ITEMS ─────────────────────── */
.item {
flex-grow: 1; /* Grow to fill remaining space */
flex-shrink: 1; /* Shrink if container is too small */
flex-basis: 200px; /* Starting size before grow/shrink */
flex: 1 1 200px; /* Shorthand */
align-self: flex-end; /* Override container's align-items */
order: 2; /* Visual reordering */
}
Common Flexbox patterns:
/* Center anything on the page */
.page {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
/* Navbar: logo left, links right */
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 24px;
height: 64px;
}
/* Equal-width columns */
.columns {
display: flex;
gap: 24px;
}
.columns > * { flex: 1; }
/* Responsive wrapping cards */
.cards {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.card { flex: 1 1 280px; } /* min 280px before wrapping */
💡
Flex vs Grid: Use Flexbox when you need one-axis control (row or column). Use Grid when you need two-axis control (rows AND columns at the same time).