What Is CSS Flexbox?
CSS Flexbox (Flexible Box Layout) is a one-dimensional layout model that lets you arrange items in rows or columns with powerful alignment and spacing controls. It's one of the most essential tools in any web developer's toolkit, replacing older float-based layouts with something far more intuitive.
Table of Contents
- Setting Up the Flex Container
- Flex Direction
- Alignment & Justification
- Controlling Flex Items
- Practical Examples
Setting Up the Flex Container
To start using Flexbox, apply display: flex to a parent element. All direct children automatically become flex items.
.container {
display: flex;
}
That single line transforms how child elements are laid out — they'll line up horizontally by default.
Flex Direction
The flex-direction property controls the main axis — the direction flex items are placed.
- row (default) — items placed left to right
- row-reverse — items placed right to left
- column — items stacked top to bottom
- column-reverse — items stacked bottom to top
Alignment & Justification
Two properties handle alignment along each axis:
| Property | Axis | Common Values |
|---|---|---|
justify-content | Main axis | flex-start, center, space-between, space-around |
align-items | Cross axis | stretch, center, flex-start, flex-end |
To center an element both vertically and horizontally — something that used to be notoriously tricky — Flexbox makes it trivial:
.container {
display: flex;
justify-content: center;
align-items: center;
}
Controlling Flex Items
Individual flex items can be controlled with these key properties:
- flex-grow — how much an item expands to fill available space (e.g.,
flex-grow: 1lets it grow) - flex-shrink — how much an item shrinks when space is limited
- flex-basis — the default size of an item before growing/shrinking
- align-self — override alignment for a single item
The shorthand flex: 1 is equivalent to flex-grow: 1; flex-shrink: 1; flex-basis: 0% and is commonly used to make items share space equally.
Practical Examples
Responsive Navigation Bar
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
}
Card Grid with Equal Heights
.card-row {
display: flex;
gap: 1.5rem;
flex-wrap: wrap;
}
.card {
flex: 1 1 250px;
}
Using flex-wrap: wrap combined with a flex-basis creates a responsive card layout without media queries.
Key Takeaways
- Apply
display: flexto the parent container, not the items. - Use
justify-contentfor horizontal spacing andalign-itemsfor vertical alignment. - Use
flex-wrap: wrapto allow items to wrap onto multiple lines. - The
gapproperty is the cleanest way to add space between flex items.
Flexbox is best for one-dimensional layouts. When you need both rows and columns, consider pairing it with CSS Grid for the full picture.