Flexbox Fundamentals
Flexbox is a one-dimensional layout system for distributing space along a single axis (row or column). It replaced the old float-based layouts and solves problems like vertical centering, equal-height columns, and flexible spacing — things that were notoriously difficult before Flexbox.
How Flexbox Works
- display: flex — Turns an element into a flex container. Direct children become flex items
- Main axis — The primary direction of layout. Default is horizontal (row). Set by flex-direction
- Cross axis — Perpendicular to the main axis. Vertical in row direction, horizontal in column direction
- flex-direction — row (default, horizontal), column (vertical), row-reverse, column-reverse
- Flex container — The parent element with display: flex. Controls alignment and distribution
- Flex items — The direct children of a flex container. They flex (grow/shrink) to fill space
- gap — Space between flex items: gap: 16px. Much cleaner than margin hacks
Basic Flexbox Code
/* Basic flex container */
.container {
display: flex;
gap: 16px;
}
/* Change direction */
.vertical { flex-direction: column; }
.reversed { flex-direction: row-reverse; }
/* Flex items automatically share space */
.flex-example {
display: flex;
gap: 12px;
}
.flex-example > div {
/* Items sit side by side, using their content width */
padding: 16px 24px;
background: #f0f4f8;
border-radius: 8px;
}Try It Yourself: Flexbox Playground
Tip
Use the gap property instead of margins for spacing flex items. gap: 20px creates space only BETWEEN items — no extra margin on the outer edges. This eliminates the need for the old :first-child/:last-child margin hacks entirely.
Flexbox is ideal for one-dimensional layouts (row or column)
Common Mistake
Applying display: flex to the CHILD instead of the parent. Flexbox is applied to the CONTAINER and its direct children become flex items automatically. Adding display: flex to a child just makes IT a flex container for ITS children, not for its siblings.
Practice Task
Create a flex container with 4 colored boxes. Try changing: (1) flex-direction between row and column, (2) gap between 8px and 32px, (3) adding flex-wrap: wrap and resizing the browser. Observe how items reflow and share space automatically.
Quick Quiz
Key Takeaways
- Flexbox is a one-dimensional layout system for distributing space along a single axis (row or column).
- display: flex — Turns an element into a flex container. Direct children become flex items
- Main axis — The primary direction of layout. Default is horizontal (row). Set by flex-direction
- Cross axis — Perpendicular to the main axis. Vertical in row direction, horizontal in column direction