CSS Flexbox is a one-dimensional layout system designed to align, distribute, and wrap items neatly along a single row or column. Setting display: flex; on a parent container immediately unlocks effortless horizontal spacing, vertical centering, and equal-height cards without float hacks.
flowchart LR
FC["Flex Container (display: flex)"] --> MA["Main Axis (justify-content)"]
FC --> CA["Cross Axis (align-items)"]
MA --> D["Row (left -> right) or Column (top -> bottom)"]
CA --> A["Perpendicular alignment (center, stretch, flex-start)"]
flex-direction: Sets the main axis (row default, or column).justify-content: Distributes items along the main axis (flex-start, center, space-between, space-evenly).align-items: Aligns items along the perpendicular cross axis (stretch, center, flex-start).flex-wrap: wrap: Allows items to wrap gracefully onto new lines instead of overflowing narrow screens.gap: Adds uniform spacing between flex items (gap: 16px;) without messy outer margins.flex: 1: Placed on child items so they grow evenly to fill remaining row space..card-row {
display: flex;
flex-wrap: wrap;
gap: 16px;
align-items: stretch;
}
.card-item {
flex: 1 1 240px;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 18px;
background-color: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 8px;
}
min-width: 0 on flex children with long text or code: By default, flex items refuse to shrink narrower than long unbroken words (min-width: auto); add min-width: 0; to allow truncation or wrapping.justify-content expecting vertical alignment in a row: justify-content always follows the main axis (horizontal in row, vertical in column), while align-items follows the cross axis.gap: gap works across all modern browsers in both Flexbox and Grid without extra margins on the first or last child.flex: 1; is shorthand for flex-grow: 1; flex-shrink: 1; flex-basis: 0%;, allowing items to divide available space equally regardless of initial text length.
Use Flexbox for one-dimensional toolbars, navbars, and button groups where content size drives layout; use CSS Grid for two-dimensional page shells and structured card grids.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.