Skip to the workspace
Pebellslearn by building
CSS  ›  Lesson

Layout with Flexbox and Grid

CSS 16 minFlexbox arranges items along one axis with justify-content and align-items, while grid places items into rows and columns defined on the parent.

frontend / Layout with Flexbox and Grid

Explore each scene at your own pace.

01 · The rule

The rule

Layout with Flexbox and Grid

The bakery page needs a navigation bar with the logo on the left and links on the right, and a menu of cards laid out in neat rows. For years, layouts like these took fragile tricks. Modern CSS gives you two tools built for the job, and the only real skill is knowing which one to reach for.

The rule

Flexbox arranges items along one line; grid places them in rows and columns.

Flexbox works in one direction at a time. Set it on the parent:

.site-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}
  • The main axis runs in the flex-direction: row (left to right, the default) or column (top to bottom).
  • justify-content spreads items along the main axis: flex-start, center, space-between and so on.
  • align-items lines them up on the other, cross axis: center puts a small logo and taller links on one middle line.
  • gap sets the space between items.
  • On a child, flex: 1 lets it grow to fill leftover space.

Grid works in two directions at once. You define the tracks on the parent and the children fall into the cells:

.menu {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1.5rem;
}
  • grid-template-columns defines the columns. 1fr means one fraction of the free space, so repeat(3, 1fr) makes three equal columns.
  • Rows are created automatically as more cards arrive.
  • A child can span tracks: grid-column: span 2 makes a featured card two columns wide.

A handy pattern lets the number of columns adjust by itself:

grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));

This fits as many columns of at least 220 pixels as the space allows.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.