CSS

Build Responsive Image Galleries with auto-fit and minmax

Effortlessly create dynamic and responsive image galleries or card layouts. Learn how CSS Grid's `auto-fit` and `minmax` properties adapt column count based on screen size.

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px; /* Space between grid items */
  padding: 20px;
}

.gallery-item {
  border: 1px solid #ddd;
  padding: 10px;
  text-align: center;
  background-color: #f9f9f9;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.gallery-item img {
  max-width: 100%;
  height: auto;
  display: block; /* Remove extra space below image */
  margin-bottom: 10px;
}
How it works: This snippet showcases how to build a highly responsive grid layout using `grid-template-columns` with `repeat(auto-fit, minmax(250px, 1fr))`. `auto-fit` automatically adjusts the number of columns to fit the available space, while `minmax(250px, 1fr)` ensures each column is at least 250px wide but can expand to fill remaining space equally. This is perfect for galleries, product listings, or card layouts that need to adapt seamlessly to different screen sizes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs