CSS

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

Build dynamic, responsive grid layouts that automatically adjust the number of columns based on available space using CSS Grid's `repeat(auto-fit, minmax(...))` function.

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

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

<!-- 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 class="grid-item">Item 6</div>
</div>
How it works: This snippet creates a responsive grid layout that adapts to different screen sizes. The `grid-template-columns: repeat(auto-fit, minmax(250px, 1fr))` property is key: `auto-fit` automatically creates as many columns as can fit, while `minmax(250px, 1fr)` ensures each column is at least 250px wide but can grow up to `1fr` (an equal fraction of the available space). This makes the grid fluidly adjust column count and width.

Need help integrating this into your project?

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

Hire DigitalCodeLabs