CSS

Responsive Image Gallery with CSS Grid auto-fit and minmax

Create a flexible image gallery that automatically adjusts the number of columns based on screen size using CSS Grid's `auto-fit` and `minmax` functions for optimal responsiveness.

.gallery {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
      gap: 16px; /* Space between grid items */
      padding: 20px;
      max-width: 1200px;
      margin: 0 auto;
    }

    .gallery-item {
      overflow: hidden;
      border-radius: 8px;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }

    .gallery-item img {
      width: 100%;
      height: 200px; /* Fixed height for consistent look */
      object-fit: cover; /* Crop images to fit */
      display: block;
    }

    /* --- HTML Structure --- */
    <div class="gallery">
      <div class="gallery-item"><img src="https://via.placeholder.com/300x200?text=Image+1" alt="Image 1"></div>
      <div class="gallery-item"><img src="https://via.placeholder.com/300x200?text=Image+2" alt="Image 2"></div>
      <div class="gallery-item"><img src="https://via.placeholder.com/300x200?text=Image+3" alt="Image 3"></div>
      <div class="gallery-item"><img src="https://via.placeholder.com/300x200?text=Image+4" alt="Image 4"></div>
      <div class="gallery-item"><img src="https://via.placeholder.com/300x200?text=Image+5" alt="Image 5"></div>
      <div class="gallery-item"><img src="https://via.placeholder.com/300x200?text=Image+6" alt="Image 6"></div>
    </div>
How it works: This snippet uses CSS Grid to create a responsive image gallery. `display: grid` initiates the grid container. `grid-template-columns: repeat(auto-fit, minmax(150px, 1fr))` is key: `auto-fit` automatically creates as many columns as possible to fill the available space, while `minmax(150px, 1fr)` ensures each column is at least 150px wide but can grow to fill available fractional space (`1fr`). `gap` adds spacing between items, and `object-fit: cover` ensures images fill their designated area without distortion.

Need help integrating this into your project?

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

Hire DigitalCodeLabs