CSS Intermediate: Layout and Responsive Design
CSS Grid: Two-Dimensional Layout
In this lesson you will
- Create a grid with rows and columns
- Use the fr unit, repeat and minmax
- Place items by spanning columns and rows
Introduction
Flexbox arranges items along one line. CSS Grid works in two dimensions: rows and columns at once. It is perfect for whole page layouts, photo galleries and dashboards.
The simple explanation
Grid lets you draw an invisible table of rows and columns, then drop items into it.
display: grid makes the container a grid. grid-template-columns defines the columns. Items fill the cells automatically, row after row.
Quick quiz
What does grid-template-columns: 1fr 1fr 1fr create?
The fr unit and repeat
fr means a fraction of the free space. 2fr 1fr makes the first column twice as wide as the second. You can also mix units.
HTML
grid-template-columns: 200px 1fr; /* fixed sidebar, flexible main */
grid-template-columns: repeat(3, 1fr); /* same as 1fr 1fr 1fr */repeat(3, 1fr) is a shorter way to write three equal columns.
Spanning cells
An item can stretch over several columns or rows with grid-column and grid-row.
Responsive galleries without media queries
This one line is worth remembering:
HTML
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));It says: "Fit as many columns as you can, each at least 140px wide, and let them share the leftover space." Try it, then make your window wider and narrower.
place-items: center on a grid centres its content both ways.
Quick quiz
Which is the better choice for laying out rows and columns together?
Flexbox or Grid?
- One direction at a time (a row of buttons, a menu): Flexbox.
- Rows and columns (page layout, galleries): Grid.
- They work well together. A grid of cards, each laid out with flexbox, is very common.
Try it yourself
Make a page layout: a header that spans both columns, a narrow sidebar and a main area. Add grid-column: 1 / -1 to the header so it spans the full width.
Summary
display: gridandgrid-template-columnscreate a grid.frshares free space, andrepeat()avoids repetition.grid-column: span 2stretches an item.repeat(auto-fit, minmax(...))builds responsive galleries.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading