CSS

Create Dynamic Responsive Grids with auto-fit and minmax()

Build flexible and dynamic grid layouts using `grid-template-columns: repeat(auto-fit, minmax(size, 1fr))` for image galleries or variable content.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Grid with Auto-Fit</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="grid-container">
        <div class="grid-item">Item 1</div>
        <div class="grid-item">A Longer Item 2</div>
        <div class="grid-item">Item 3</div>
        <div class="grid-item">Item 4 with More Text</div>
        <div class="grid-item">Item 5</div>
        <div class="grid-item">Item 6</div>
        <div class="grid-item">Item 7</div>
        <div class="grid-item">Last Item 8</div>
    </div>
    <p>Resize your browser window to see the grid items automatically adjust their column count and size.</p>
</body>
</html>

body {
    font-family: sans-serif;
    margin: 20px;
    background-color: #f4f4f4;
}

.grid-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); /* Key property */
    gap: 20px; /* Space between grid items */
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.grid-item {
    background-color: #007bff;
    color: white;
    padding: 20px;
    text-align: center;
    border-radius: 5px;
    font-size: 1.2em;
    display: flex; /* Using flexbox inside grid item for centering content */
    justify-content: center;
    align-items: center;
    min-height: 100px;
}
How it works: This snippet showcases a powerful CSS Grid technique for creating highly flexible and responsive layouts without media queries. The `grid-template-columns: repeat(auto-fit, minmax(200px, 1fr))` property is the core. `repeat()` with `auto-fit` tells the grid to create as many columns as can fit into the container. `minmax(200px, 1fr)` defines the size of each column: it should be at least `200px` wide, but if there's extra space, it can grow up to `1fr` (fraction of the available space), ensuring all columns have equal width. This dynamically adjusts the number of columns and their widths based on the viewport size, making it ideal for displaying collections of items like images, articles, or products.

Need help integrating this into your project?

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

Hire DigitalCodeLabs