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;
}Change it. See why.
Adjust the controls and compare the result with the CSS. Changes stay only in this page’s memory.
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
W3C — CSS Grid Layout (new tab)
Keep exploring
- CSS · Guide
Find the source of horizontal overflowFix the oversized element instead of hiding the symptom.
- CSS · Guide
Why a huge z-index can still loseUnderstand the group an element belongs to before raising its number.