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

  1. Setting Up the Flex Container
  2. Flex Direction
  3. Alignment & Justification
  4. Controlling Flex Items
  5. 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:

PropertyAxisCommon Values
justify-contentMain axisflex-start, center, space-between, space-around
align-itemsCross axisstretch, 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: 1 lets 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: flex to the parent container, not the items.
  • Use justify-content for horizontal spacing and align-items for vertical alignment.
  • Use flex-wrap: wrap to allow items to wrap onto multiple lines.
  • The gap property 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.