CSS Grids [2d]

CSS Grid lays out a page in two dimensions at once: you define rows and columns on a container and place its children into that grid โ€” by cell, by area name, or automatically. Where Flexbox distributes items along one line and wraps, Grid controls both axes together, which makes page skeletons, card galleries and forms with aligned labels far simpler and removes many wrapper elements. As a rule of thumb: Flexbox for one-dimensional flows, Grid for two-dimensional structures.

Important

Work on this lesson in teacher mode.

Learning goals

  • You can explain the difference between one-dimensional and two-dimensional layout, and pick Flexbox or Grid for a given layout accordingly.
  • You can explain the Grid model โ€” container, tracks, lines, cells and areas โ€” and the difference between explicit and implicit tracks.
  • You can define a grid with rows, columns and gaps, and place items by line numbers or by named areas.
  • You can build common page layouts with Grid, e.g. a header/sidebar/content/footer page or a gallery of cards, with fewer wrapper elements than Flexbox would need.
  • You can inspect and debug a grid layout with the browser's DevTools.

Resources

Read what's new to you, skim what's familiar, skip what you already master. Stop when you can meet the learning goals.

Your agent can also generate an overview, a tutorial or an explanation for anything here, tailored to what you already know. Just ask.

Pick one guide

Practice and reference

Exercises

Arrange cards with display: grid

  • Go back to the Practice: Cards exercise of the BEM pattern card
  • Rework your previous solution. It should now use display: grid wherever possible and reasonable

Tip

Can you reduce the number of container elements in your DOM by switching from Flexbox to Grid?

Alternative: Compare layouting strategies

If your BEM solution already made appropriate use of display: grid, you can opt to solve this exercise instead. Position the gallery items of the card "CSS: Fluid and responsive layouts " once with each of the following different layouting algortihms Show archive.org snapshot :

  • display:grid (the container)
  • display:flex (the container)

Talk with your mentor about the pros and cons of each approach.

Michael Leimstรคdtner