CSS

Create a Responsive Grid with `auto-fit` and `minmax`

Build a flexible and responsive grid layout that automatically adjusts column count based on viewport size, using CSS Grid's `auto-fit` and `minmax` functions.

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  padding: 20px;
  background-color: #f0f0f0;
}

.grid-item {
  background-color: #ffffff;
  border: 1px solid #ddd;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  border-radius: 8px;
}
How it works: This code creates a highly responsive grid where items automatically adjust their number of columns based on available space. `display: grid` enables the grid context. `grid-template-columns: repeat(auto-fit, minmax(250px, 1fr))` is the core: `auto-fit` tells the grid to fill the available space with as many columns as possible, and `minmax(250px, 1fr)` ensures each column is at least 250px wide but never larger than 1 fraction of the available space, creating a fluid and adaptable layout. The `gap` property provides consistent spacing between 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