CSS

Responsive Grid with Dynamic Column Sizing

Build flexible and responsive grid layouts that automatically adjust the number of columns based on available space and item minimum width using `auto-fit` or `auto-fill` and `minmax()` in CSS Grid.

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1.5rem;
  padding: 1rem;
}

.grid-item {
  background-color: #e0e0e0;
  padding: 1rem;
  border-radius: 8px;
  text-align: center;
}

/* Using auto-fill instead of auto-fit */
.grid-fill-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 1rem;
  padding: 1rem;
  background-color: #f0f0f0;
}
How it works: This snippet demonstrates creating highly responsive grid layouts that adapt column counts based on container width without explicit media queries. The `repeat(auto-fit, minmax(200px, 1fr))` property ensures that columns are created to fit items with a minimum width of 200px, taking up equal fractional space (`1fr`) when more space is available. `auto-fit` expands items to fill remaining space if there aren't enough items to fill a row, while `auto-fill` leaves empty tracks. This is ideal for dynamic galleries, card layouts, or any scenario where item count per row needs to adjust automatically.

Need help integrating this into your project?

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

Hire DigitalCodeLabs