← Back to all snippets
CSS

Fluid Image Gallery with Auto-Fit and Aspect Ratio

Create a responsive image gallery or grid that automatically adjusts column count based on available space using `grid-auto-fit`, ensuring images maintain a consistent aspect ratio with `aspect-ratio`.

.gallery-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 1rem;
  padding: 1rem;
}
.gallery-item {
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.gallery-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  aspect-ratio: 16 / 9;
  display: block;
}
/* HTML Structure for context:
<div class="gallery-container">
  <div class="gallery-item"><img src="image1.jpg" alt="Description"></div>
  <div class="gallery-item"><img src="image2.jpg" alt="Description"></div>
  ...
</div>
*/
How it works: This CSS creates a responsive grid layout using `grid-template-columns: repeat(auto-fit, minmax(180px, 1fr))`. `auto-fit` allows columns to dynamically fill the available space, while `minmax(180px, 1fr)` ensures items are at least 180px wide and grow to take equal space. The `aspect-ratio: 16 / 9` on the `img` tag guarantees all images maintain a consistent 16:9 aspect ratio, preventing layout shifts and improving visual consistency in the gallery.

Need help integrating this into your project?

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

Hire DigitalCodeLabs