Aspect Ratios in CSS Grid
You'll learn how to combine aspect-ratio with CSS Grid to build responsive image galleries where every item maintains consistent proportions automatically.
The Core Idea
When building image galleries with CSS Grid, you often want each grid item to maintain the same aspect ratio—say, perfect squares or 16:9 rectangles—regardless of how the grid resizes. By combining the aspect-ratio property you've already learned with Grid's flexible sizing, you can create galleries that adapt beautifully across screen sizes while keeping visual consistency.
How It Works
CSS Grid handles the layout (columns, gaps, responsive flow), while aspect-ratio ensures each item maintains its shape. Apply aspect-ratio to the grid items (or images inside them), and Grid will respect those proportions as it calculates item sizes.
Here's a basic pattern:
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
}
.gallery-item {
aspect-ratio: 1 / 1; /* Square items */
}
.gallery-item img {
width: 100%;
height: 100%;
object-fit: cover; /* Crop images to fit */
}
The grid dynamically creates columns that fit the viewport, while every item stays square thanks to aspect-ratio: 1 / 1. The images inside use object-fit: cover to fill their containers without distortion.
Why This Matters
Think of it like bookshelves with adjustable width but fixed shelf height—the shelves expand or contract horizontally as the wall size changes, but every shelf stays exactly the same height. Your images work the same way: flexible positioning, consistent shape.
Key Takeaway: Combining aspect-ratio with CSS Grid gives you responsive galleries with predictable proportions—Grid handles the flexible layout, while aspect-ratio locks in consistent shapes for every item.