CSS

CSS Grid Layout Explained

What Grid Solves

CSS Grid is a two-dimensional layout system — it controls rows and columns at the same time, making it ideal for full page layouts and card galleries.

Basic Grid Setup

.gallery { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }

This creates three equal-width columns with 20px of space between every item, automatically wrapping to new rows.

Responsive Grids Without Media Queries

One of Grid’s best tricks is auto-fill/auto-fit combined with minmax() — the number of columns adjusts automatically based on available space:

.gallery { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; }

Naming and Spanning Areas

.page { display: grid; grid-template-columns: 250px 1fr; grid-template-areas: "sidebar header" "sidebar content"; } .sidebar { grid-area: sidebar; } .header { grid-area: header; } .content { grid-area: content; }

Positioning Individual Items

.featured { grid-column: span 2; /* takes up 2 columns */ grid-row: span 2; /* takes up 2 rows */ }

Grid vs Flexbox, Revisited

A common real-world pattern: Grid for the overall page skeleton, Flexbox for aligning content inside individual components. They’re not competitors — they’re complementary tools.

Practice Exercise

Build a 3-column responsive photo gallery using auto-fit and minmax() that collapses to a single column on narrow screens without writing a media query.

Leave a Reply

Your email address will not be published. Required fields are marked *