CSS Grid
CSS Grid is a two-dimensional layout system, letting you define rows and columns together and place items precisely within that structure.
Defining a Grid
Setting display: grid on a container, then defining columns and rows, gives you full control over a two-dimensional layout that would require far more markup and hacks with flexbox alone.
.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 24px;
}
@media (max-width: 700px) {
.gallery {
grid-template-columns: 1fr;
}
}
auto-fit and minmax
Combining repeat(auto-fit, minmax(...)) creates a genuinely responsive grid without a single media query — columns automatically wrap based on available space and a minimum item width.
.cards-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 20px;
}
Common Mistakes
- Using grid for simple one-dimensional layouts where flexbox would be simpler and sufficient.
- Forgetting units in
grid-template-columns, e.g. writing1fr 1fr 1frincorrectly as plain numbers. - Not accounting for grid items that don't fit evenly, leaving unexpected empty cells.
- Confusing grid-gap (older syntax) with the modern unprefixed gap property, which now works for both grid and flexbox.
Professional Tip
As a rule of thumb: reach for flexbox when you're arranging items along a single row or column, and reach for grid when you need to control both rows and columns together, like a photo gallery or a full page layout.
Your Turn
Build a responsive photo gallery using grid-template-columns with repeat(auto-fit, minmax(...)) so it reflows automatically from three columns down to one as the viewport shrinks.
Mini Quiz
What makes CSS Grid different from Flexbox at a fundamental level?