Flexbox or Grid? How to choose without the headache

Both are for layout, and the answer isn't "pick one". Here's one simple question you can ask every time you're not sure.

CSS · 5 min read · Hyper Sheets

Almost everyone who's new to layout has asked this. The answer often gets made complicated, but all you need is one question to bring along every time you lay something out.

One question: one direction or two?

If you're arranging just one row or one column, use Flexbox. If you need rows and columns lined up at the same time, use Grid. The rest is detail.

Flexbox: size comes from the content

Flexbox lays items out along one axis. Each item can grow or shrink to fit its content, which makes it a good fit for a navbar, a row of buttons, or a line of icons and text.

.nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

With flex-wrap: wrap, items can drop onto a new line. But each line is worked out on its own, so the columns aren't guaranteed to line up.

Grid: size comes from the layout

Grid draws the frame first, and then the items fill its cells. Rows and columns are set together, so every item's edges line up both down and across.

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 16px;
}

Try it yourself

The same five cards, two ways. Drag the container's width, then watch the last row.

In Flexbox, the cards on the last row stretch to fill the leftover space, so they end up a different size from the cards above them. In Grid, each card stays in its own column, and the leftover space is left empty.

Usually used together

A tidy page layout almost always uses both: Grid for the big frame, Flexbox for the content inside each part.

.card-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}
.card {
  display: flex;
  flex-direction: column;
}
.card .button {
  margin-top: auto; /* the button always sits at the bottom */
}

In short

Cek pemahaman

  1. A navbar has a logo on the left and three links on the right, all centred on one line. Which do you use? (Flexbox / Grid)
  2. A photo gallery whose columns have to line up across every row. Which do you use? (Flexbox / Grid)

All posts on the Hyper Sheets Blog