Chapter 04 of 09Part 2 · Layout

Flexbox vs grid: laying out a page

Flexbox lines things up in a row or a column, grid draws rows and columns at once. Learn when to use each.

11 minBy Zuzo StudioUpdated

11 min

In this chapter you will

  • tell when a layout is a flexbox job and when it is a grid job
  • align and space items with justify-content, align-items and gap
  • build columns that adapt to the screen with repeat, minmax and auto-fit

Before you startThis builds on The cascade and the CSS box model.

Check your understanding

3 questions

Q1You have six product cards and want them to line up in neat columns, including the last row. Which is the better fit?

Show the answer

Grid with grid-template-columns Grid defines columns first, so every card sits in a column and the rows line up whatever the number of cards.

Q2In a flex container with flex-direction: column, what does justify-content: center do?

Show the answer

Centres the items vertically, along the main axis justify-content always works along the main axis, and in a column the main axis runs top to bottom. The container needs spare height for it to show.

Q3What does repeat(auto-fit, minmax(16rem, 1fr)) do?

Show the answer

Fits as many columns of at least 16rem as the container allows, and shares out any spare width auto-fit decides the number of columns from the space available, and the 1fr maximum lets them stretch to fill the row.

Key takeaways

  1. Flexbox lays items out in one dimension, a row or a column; grid lays them out in rows and columns at the same time.
  2. Flexbox works from the content out, grid works from the layout in, and most pages use both, chosen box by box.
  3. In flexbox, justify-content works along the main axis and align-items along the cross axis.
  4. repeat(auto-fit, minmax(16rem, 1fr)) gives you responsive columns without a single media query.
  5. Keep the HTML in reading order and use layout to arrange it, not to reorder it.
Up next · Chapter 05 · 10 min Responsive web design, from phone to wide screen One page that works on every screen: the viewport tag, mobile first media queries, fluid type and images that fit.

02FAQ

Questions on this chapter

Something else on your mind? Email the studio and a designer, not a salesperson, replies within a day.

Should I use flexbox or grid?

Use flexbox when you are lining items up in a single row or column and their size depends on their content, like a menu or a row of buttons. Use grid when items need to line up in rows and columns at the same time, like cards or a page with a sidebar. Most pages use both.

Is CSS grid better than flexbox?

Neither is better; they solve different problems. Grid is two dimensional and starts from the layout, flexbox is one dimensional and starts from the content, and they nest inside each other without any trouble.