← Back to all snippets
CSS

Responsive Image Gallery with CSS Grid and Media Queries

Build a responsive image gallery using CSS Grid that adapts gracefully to different screen sizes. This snippet utilizes `grid-template-columns` and media queries for optimal display.

.gallery {
    display: grid;
    grid-template-columns: repeat(2, 1fr); /* Default to 2 columns on small screens */
    gap: 15px; /* Spacing between grid items */
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

.gallery-item img {
    width: 100%;
    height: 200px; /* Fixed height for uniformity */
    object-fit: cover; /* Ensures images cover the area without distortion */
    display: block; /* Removes extra space below image */
    border-radius: 8px;
}

@media (min-width: 768px) {
    .gallery {
        grid-template-columns: repeat(3, 1fr); /* 3 columns on medium screens */
    }
}

@media (min-width: 1024px) {
    .gallery {
        grid-template-columns: repeat(4, 1fr); /* 4 columns on large screens */
    }
}
How it works: This snippet creates a responsive image gallery using CSS Grid. It establishes a default of two columns on smaller screens using `grid-template-columns: repeat(2, 1fr)`. Media queries are then employed to dynamically adjust the number of columns: to three columns for medium-sized screens (`min-width: 768px`) and to four columns for larger screens (`min-width: 1024px`). The `gap` property ensures consistent spacing between images, and `object-fit: cover` within `gallery-item img` maintains image aspect ratios while filling the designated area, making it ideal for visual content.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs