CSS
Build a Responsive Image Gallery with Consistent Aspect Ratios using CSS Grid
Implement a dynamic and responsive image gallery using CSS Grid, ensuring all images maintain a consistent aspect ratio while fitting beautifully into the layout with `object-fit`.
.image-gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); /* Responsive columns */
gap: 1rem; /* Space between grid items */
padding: 1rem;
}
.gallery-item {
display: block; /* Ensure image takes full width of parent */
overflow: hidden; /* Hide parts of image that don't fit aspect ratio */
position: relative;
background-color: #e0e0e0; /* Placeholder background */
border-radius: 8px;
}
.gallery-item::before {
content: '';
display: block;
padding-top: 75%; /* 4:3 aspect ratio (height is 75% of width) */
/* For 1:1, use padding-top: 100%; */
/* For 16:9, use padding-top: 56.25%; */
}
.gallery-item img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover; /* Crop image to fit without distortion */
border-radius: 8px;
transition: transform 0.3s ease;
}
.gallery-item img:hover {
transform: scale(1.05);
}
/* <!-- HTML STRUCTURE --> */
<div class="image-gallery">
<div class="gallery-item"><img src="https://via.placeholder.com/600x450/FF5733/FFFFFF?text=Image+1" alt="Image 1"></div>
<div class="gallery-item"><img src="https://via.placeholder.com/800x600/33FF57/FFFFFF?text=Image+2" alt="Image 2"></div>
<div class="gallery-item"><img src="https://via.placeholder.com/700x525/3357FF/FFFFFF?text=Image+3" alt="Image 3"></div>
<div class="gallery-item"><img src="https://via.placeholder.com/900x675/FF33A1/FFFFFF?text=Image+4" alt="Image 4"></div>
<div class="gallery-item"><img src="https://via.placeholder.com/500x375/33FFF2/FFFFFF?text=Image+5" alt="Image 5"></div>
<div class="gallery-item"><img src="https://via.placeholder.com/1000x750/FFD133/FFFFFF?text=Image+6" alt="Image 6"></div>
</div>
How it works: This snippet creates a responsive image gallery using CSS Grid. `grid-template-columns: repeat(auto-fill, minmax(250px, 1fr))` ensures a flexible number of columns, each at least 250px wide, and filling available space. Each `gallery-item` maintains a consistent aspect ratio (4:3 in this example, set by `padding-top: 75%` on a pseudo-element). The `img` element is absolutely positioned inside, covering its parent entirely, and `object-fit: cover` ensures images fill the container without distortion, cropping as needed.