Summary - Card grid
Build a responsive card grid with flexbox.
Summary — Card grid
In this group you learned how flex items grow, shrink and order themselves, how to align a single item, and how to space items apart. Now we will combine these into a responsive card grid.
The grid should: let cards grow equally, never shrink, start at 200 pixels wide, and keep 1 rem of space between them when they wrap.
Which properties will we use?
First we will make the .cards container a flex container and turn on wrapping with flex-wrap: wrap. We will add gap: 1rem between cards so they stay tidy even when they wrap.
For each card we will write flex: 1 0 200px. This makes the card share free space proportionally, never shrink, and start at 200 pixels.
Exercise Set up the card grid container
Set up a .cards flex container. Add display: flex, flex-wrap: wrap and gap: 1rem. No cards needed yet; just write the container.
Show example solution
/* card grid container */
.cards {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
Exercise Give cards flex: 1 0 200px
Add a .cards > .card selector and write flex: 1 0 200px. Each card now starts at 200 pixels, never shrinks, and shares free space evenly.
Show example solution
/* make the cards flexible */
.cards > .card {
flex: 1 0 200px;
}
Test yourself
-
Match each piece of the grid to its role
- flex-wrap: wrap
- Turns on wrapping
- gap: 1rem
- Space between items
- flex: 1 0 200px
- Grow, shrink, basis
- display: flex
- Flex container
-
What does flex: 1 0 200px mean?
- grow 1, shrink 0, basis 200px
- grow 0, shrink 1, basis 200px
- grow 1, shrink 200, basis 0
- grow 200, shrink 1, basis 0
Show answer
grow 1, shrink 0, basis 200px — Correct. The flex shorthand takes grow, shrink and basis in that order.