CSS

Responsive Grid with auto-fit and minmax()

Create a flexible and responsive CSS Grid layout that automatically adjusts column count based on viewport size, ensuring optimal item display.

/* HTML Structure: */
/* <div class="grid-container">
/*   <div class="grid-item">Item 1</div>
/*   <div class="grid-item">Item 2</div>
/*   <div class="grid-item">Item 3</div>
/*   <div class="grid-item">Item 4</div>
/*   <div class="grid-item">Item 5</div>
/* </div> */

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  /* Optional: Adds space between grid items */
  gap: 16px;
}

.grid-item {
  padding: 20px;
  background-color: #f0f0f0;
  border: 1px solid #ccc;
  text-align: center;
}
How it works: This snippet creates a responsive grid layout. The `display: grid;` property turns the container into a grid. `grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));` is the core of its responsiveness. `auto-fit` automatically fits as many columns as possible into the available space. `minmax(250px, 1fr)` ensures that each column is at least `250px` wide but will expand to fill available space (`1fr`) if there's room, maintaining equal column widths. The `gap` property adds space between grid items, making the layout cleaner.

Need help integrating this into your project?

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

Hire DigitalCodeLabs