CSS

Build a Flexible N-Column Grid Layout with `repeat` and Media Queries

Create adaptable grid layouts that automatically adjust the number of columns based on screen size, using CSS Grid's `repeat()` function and media queries for precise control.

.grid-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* Default: 4 equal columns */
  gap: 20px;
  padding: 20px;
}

.grid-item {
  background-color: #e0f2f7;
  border: 1px solid #b3e5fc;
  padding: 20px;
  text-align: center;
}

@media (max-width: 1024px) {
  .grid-container {
    grid-template-columns: repeat(3, 1fr); /* 3 columns on medium screens */
  }
}

@media (max-width: 768px) {
  .grid-container {
    grid-template-columns: repeat(2, 1fr); /* 2 columns on tablets */
  }
}

@media (max-width: 480px) {
  .grid-container {
    grid-template-columns: repeat(1, 1fr); /* Single column on mobile */
  }
}
How it works: This snippet provides a robust solution for creating responsive multi-column layouts using CSS Grid. Instead of `auto-fit` or `minmax`, it explicitly defines the number of columns using `grid-template-columns: repeat(N, 1fr)`. This creates N columns, each taking up an equal fraction of the available space. By using media queries, the value of `N` can be dynamically changed at different breakpoints, allowing the layout to adapt gracefully from a desktop view (e.g., 4 columns) down to a mobile view (e.g., 1 column), giving precise control over column count.

Need help integrating this into your project?

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

Hire DigitalCodeLabs