CSS

CSS Grid: Fully Responsive N-Column Layout with `auto-fit` and `minmax()`

Create a dynamic, multi-column grid that automatically adjusts the number of columns based on screen width using `grid-template-columns`, `repeat(auto-fit, minmax())` for image galleries or product listings.

.grid-container {
  display: grid;
  /*
   * auto-fit: Fills available space, if items are few, they stretch to fill.
   * auto-fill: Creates as many columns as possible, even if empty.
   * minmax(250px, 1fr): Each column will be at least 250px,
   *                      and take up equal remaining space (1fr).
   * gap: Creates spacing between grid items.
   */
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px; /* Spacing between grid items */
  padding: 20px;
  background-color: #e0e0e0;
}

.grid-item {
  background-color: #fff;
  border: 1px solid #ccc;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  border-radius: 5px;
}

.grid-item img {
  max-width: 100%;
  height: auto;
  display: block;
  margin-bottom: 10px;
}

/* HTML Structure */
/*
<div class="grid-container">
  <div class="grid-item">
    <img src="https://via.placeholder.com/200x150?text=Item+1" alt="Item 1">
    <h3>Product Title 1</h3>
    <p>Short description here.</p>
  </div>
  <div class="grid-item">
    <img src="https://via.placeholder.com/200x150?text=Item+2" alt="Item 2">
    <h3>Product Title 2</h3>
    <p>More details for item 2.</p>
  </div>
  <div class="grid-item">
    <img src="https://via.placeholder.com/200x150?text=Item+3" alt="Item 3">
    <h3>Product Title 3</h3>
    <p>Discover item 3's features.</p>
  </div>
  <div class="grid-item">
    <img src="https://via.placeholder.com/200x150?text=Item+4" alt="Item 4">
    <h3>Product Title 4</h3>
    <p>Click to learn more.</p>
  </div>
  <div class="grid-item">
    <img src="https://via.placeholder.com/200x150?text=Item+5" alt="Item 5">
    <h3>Product Title 5</h3>
    <p>An amazing item!</p>
  </div>
</div>
*/
How it works: This snippet showcases CSS Grid's powerful auto-placement and responsiveness. `display: grid` makes the container a grid. The key is `grid-template-columns: repeat(auto-fit, minmax(250px, 1fr))`. `repeat()` with `auto-fit` (or `auto-fill`) allows the browser to automatically create as many columns as fit. `minmax(250px, 1fr)` ensures each column is at least 250px wide but can grow to take an equal fraction (`1fr`) of the available space, making it incredibly flexible without requiring media queries for basic column count changes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs