CSS

Responsive Grid with Dynamic Column Counts

Build a responsive grid layout that adapts the number of columns (e.g., 4-3-2-1) at different screen sizes using CSS Grid and media queries for flexible content display.

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

.grid-item {
  background-color: #f0f8ff;
  border: 1px solid #add8e6;
  padding: 20px;
  text-align: center;
  box-sizing: border-box;
}

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

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

/* 1 column on small screens */
@media (max-width: 480px) {
  .grid-container {
    grid-template-columns: repeat(1, 1fr);
  }
}
How it works: This snippet demonstrates how to create a responsive grid that changes its column count based on the screen size using CSS Grid and media queries. The `grid-template-columns: repeat(N, 1fr)` property sets N equally sized columns. By adjusting `N` within media queries, the layout fluidly adapts from 4 columns on large screens down to a single column on small screens, making it ideal for displaying collections of items like products or articles. This approach offers precise control over column numbers at specific breakpoints.

Need help integrating this into your project?

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

Hire DigitalCodeLabs