CSS · Unit 3: Layout with flexbox and grid · Lesson 4 of 6
CSS grid
Grid lays things out in rows and columns at the same time.
Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.
The idea
Grid lays things out in rows and columns at the same time. Put display: grid on the container, then grid-template-columns says how many columns and how wide.
The fr unit is a fraction of the free space. grid-template-columns: 1fr 1fr 1fr makes three equal columns; repeat(3, 1fr) says the same thing more briefly.
Use flexbox for one row or column of things, and grid for two-dimensional layouts like a photo gallery.
Worked example
CSS
.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.gallery div {
padding: 24px;
background-color: #dbeafe;
text-align: center;
}
The HTML it styles
<div class="gallery">
<div>1</div><div>2</div><div>3</div>
<div>4</div><div>5</div><div>6</div>
</div>
Key terms
- CSS grid
- display: grid lays children out in rows and columns at once.
- fr unit
- A share of the free space in a grid: 1fr 2fr makes the second column twice as wide.
Practise it in Code Academy
It has 4 exercises (multiple choice, fill in the blank and write code from a prompt) and takes about 7 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.
Every lesson is free: no ads, no lives and no paywall.