CSS

Build a Responsive Grid Gallery with Auto-Fitting Columns

Create a dynamic, responsive image gallery or card layout using CSS Grid's `repeat(auto-fit, minmax())` function, adapting flawlessly to different screen sizes.

.gallery-grid {
  display: grid;
  /* Creates auto-fitting columns, each at least 200px wide, growing to fill available space */
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1.5rem; /* Spacing between grid items */
  padding: 1rem;
  max-width: 1200px;
  margin: 0 auto;
}

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

.gallery-item img {
  max-width: 100%;
  height: auto;
  display: block;
  margin-bottom: 0.5rem;
}
How it works: This CSS Grid snippet creates a highly responsive gallery layout. The `display: grid;` property initiates the grid container. `grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));` is the core of its responsiveness: `auto-fit` automatically creates as many columns as can fit, `minmax(200px, 1fr)` ensures each column is at least 200px wide but will grow to take up an equal fraction (`1fr`) of the available space, preventing overflow. `gap` adds consistent spacing between all grid items.

Need help integrating this into your project?

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

Hire DigitalCodeLabs