A card grid should respond to its available space, not only to a list of device names. CSS Grid can create as many columns as fit while keeping each card readable. The difficult cases are usually narrow containers, long titles and images that do not respect their parent width.
repeat with auto-fit creates tracks that fit the available width and collapses empty tracks. minmax gives a lower bound and allows remaining space to be distributed. The nested min prevents a 16rem minimum from forcing overflow when the entire container is narrower than that.
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
gap: 1rem;
}
.card {
min-width: 0;
padding: 1rem;
border: 1px solid #cbd5e1;
border-radius: 0.75rem;
overflow-wrap: anywhere;
}
.card img {
display: block;
max-width: 100%;
height: auto;
}Both can create repeated tracks based on available space. auto-fit collapses empty tracks, allowing occupied tracks to stretch. auto-fill retains space for empty tracks. The better choice depends on whether a short final row should stretch or preserve the apparent column structure.
A fixed card height may look consistent with sample titles and then clip real content or break at larger text sizes. Let content determine height unless there is a clear overflow strategy. If actions need alignment, use an internal flex or grid layout instead of hiding text to force uniformity.
Large images, preformatted code and long unbroken strings can create minimum-size pressure. min-width: 0 helps a grid item shrink, but the content still needs a deliberate wrapping or scrolling rule. For code blocks, horizontal scrolling is often preferable to breaking commands unpredictably.
Resize the grid inside a narrow sidebar as well as a full-width page. Test one card, many cards, a long title and browser zoom. A design that works at 390 pixels in isolation can still overflow when nested inside a padded container.
Build six cards with deliberately different title lengths. Compare auto-fit with auto-fill when only two cards remain. At 200% zoom, verify that text and keyboard focus remain visible without horizontal page scrolling.
Explore the related Code Hacker course syllabus for structured learning. Then read Accessible HTML Form Errors with Labels and Descriptions to connect this exercise to the next skill.
MDN grid-template-columns provides the underlying API or technical guidance. Check the documentation for the version you use; examples here are small learning exercises rather than complete production implementations.
Found an issue with this guide? Send a correction with the article URL and your example. About our learning material.
Subscribe to Code Hacker and get hands-on access to 40+ premium courses — Ethical Hacking, Kali Linux, Metasploit, Network Hacking, Bug Bounty & more!