Flexbox Intro

Lay Things Out in a Row or Column

Flexbox Intro

Flexbox is the right tool for one-dimensional layout — a row of buttons, a column of cards, a centered hero.

4 min read Level 2/5 #css#flexbox#flex
What you'll learn
  • Set up a flex container
  • Switch direction
  • Use `gap` for spacing

Flexbox is built for one-dimensional layouts — a row, a column. Centering, distribution, equal-width — all easy.

The Two Roles

  • Flex container — has display: flex
  • Flex items — its direct children
.nav {
  display: flex;
  gap: 1rem;
}
<nav class="nav">
  <a href="/">Home</a>
  <a href="/about">About</a>
  <a href="/contact">Contact</a>
</nav>

Three links in a row, with 1rem of space between. That’s it.

Default Behavior

A flex container makes its children:

  • Lay out in a row (left to right)
  • Take their natural width
  • Align to the top
  • Not wrap to a new line

You’ll tweak that with properties.

Direction

.col {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

A vertical stack with spacing — without margin-bottom on every item.

Other values: row-reverse, column-reverse — flip the order.

gap — The Magic Property

gap puts space BETWEEN items, never before the first or after the last. It replaces ugly margin tricks like .item + .item { margin-left: 1rem; }.

.gallery {
  display: flex;
  gap: 1rem;             /* same gap horizontally */
  flex-wrap: wrap;
}

For different horizontal and vertical gaps:

gap: 1rem 0.5rem;     /* row-gap col-gap */
row-gap: 1rem;
column-gap: 0.5rem;

When Flex, When Grid

Flexbox is one-dimensional — items flow in one direction and wrap if they don’t fit.

Grid is two-dimensional — rows and columns at once.

Rules of thumb:

  • A nav bar, button row, breadcrumbs, tag cloud → flex
  • A photo gallery, dashboard, calendar → grid
  • A simple card with image / title / body stacked → flex column

When in doubt, try flex first — it’s usually the simpler one.

Up Next

The other flex properties — justify, align, wrap, grow.

Flex Properties →