By combining display: grid with grid-template-columns: repeat(auto-fit, minmax(..., 1fr)), you can build a highly responsive image gallery where columns automatically scale and adapt to the viewport width—without writing a single media query (@media).

Preview

Use Cases & Features

Design & UX

Customization Guide

Implementation

index.html
<div class="gallery">
<img src="/gallery/1.png" alt="Gallery image 1" class="gallery-item" />
<img src="/gallery/2.png" alt="Gallery image 2" class="gallery-item" />
<img src="/gallery/3.png" alt="Gallery image 3" class="gallery-item" />
<img src="/gallery/4.png" alt="Gallery image 4" class="gallery-item" />
<img src="/gallery/5.png" alt="Gallery image 5" class="gallery-item" />
<img src="/gallery/6.png" alt="Gallery image 6" class="gallery-item" />
</div>
styles.css
.gallery {
display: grid;
/* Automatically adjusts the number of columns to fill the container, keeping them at least 200px wide */
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
padding: 16px;
width: 100%;
box-sizing: border-box;
}

.gallery-item {
width: 100%;
/* Maintain square aspect ratio */
aspect-ratio: 1 / 1;
/* Crop to maintain aspect ratio */
object-fit: cover;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), 
            box-shadow 0.3s cubic-bezier(0.4, 0, 0.2, 1);
cursor: pointer;
}

.gallery-item:hover {
/* Subtle floating effect on hover */
transform: translateY(-4px) scale(1.02);
box-shadow: 0 12px 20px rgba(0, 0, 0, 0.1);
z-index: 10;
}

Browser Support