Understand the idea
CSS Grid arranges direct children into rows and columns. It is especially useful when a layout needs consistent tracks in both directions.
repeat avoids writing the same track definition several times. auto-fit fits as many tracks as the container allows and collapses empty ones. minmax sets a lower and upper size. min(100%, 240px) prevents the minimum track width from exceeding a narrow container.
Read the example
This is a CSS fragment. Put it in a stylesheet and supply the matching HTML described in the exercise.
.gallery {
display: grid;
grid-template-columns:
repeat(auto-fit, minmax(min(100%, 240px), 1fr));
gap: 20px;
}A small mistake, explained
What goes wrong
A fixed minimum track size can force horizontal scrolling on screens narrower than that minimum.
How to fix it. Allow the minimum to shrink to the available width, and check whether an image or long word inside a card is causing overflow.
Try it yourself
Add six cards to a .gallery container. Resize from a wide desktop window down to a narrow phone width.
Further reading
Keep exploring
- CSS · Guide
Selectors: choosing what to styleMatch the element you mean before adjusting its appearance.
- CSS · Guide
The box modelUnderstand where an element’s width really comes from.