Flexbox
Definition
A CSS layout method that makes it easy to arrange elements in rows or columns with flexible sizing and alignment.
What is Flexbox?
Flexbox (Flexible Box Layout) is a CSS layout system designed to arrange elements in one directionβeither a row or a column. It handles spacing, alignment, and sizing automatically, making layouts that used to require complex CSS achievable with just a few properties.
Before Flexbox, centering elements vertically was notoriously difficult. Now it's a single line of code.
When to Use Flexbox
Flexbox excels at:
- Aligning items horizontally or vertically
- Distributing space between elements
- Creating navigation bars
- Building card layouts that need equal heights
- Centering content perfectly
Key Concepts
Container and Items
Flexbox works on a parent-child relationship. The parent becomes a "flex container," and its direct children become "flex items."
Main Axis and Cross Axis
The main axis is the direction items flow (row or column). The cross axis is perpendicular to it. Understanding this helps with alignment.
Common Use Cases
| Pattern | What Flexbox Does |
|---|---|
| Navigation | Spaces menu items evenly across the header |
| Footer columns | Creates equal-width sections that wrap on mobile |
| Card grids | Makes all cards the same height regardless of content |
| Centering | Places content perfectly in the middle of a container |
Flexbox vs CSS Grid
Flexbox is one-dimensional (row OR column). CSS Grid is two-dimensional (rows AND columns). Use Flexbox for simpler layouts and components; use Grid for full-page layouts.
Both are widely supported in modern browsers and often used together on the same page.