CSS
Create Responsive Card Grids with CSS Grid `auto-fit`
Learn to build fully responsive grid layouts for cards or items using CSS Grid's `repeat(auto-fit, minmax())` function, adapting automatically to screen size without media queries.
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
padding: 20px;
}
.card {
background-color: #f0f0f0;
border: 1px solid #ccc;
padding: 15px;
text-align: center;
box-shadow: 2px 2px 5px rgba(0,0,0,0.1);
}
/* HTML Structure */
/*
<div class="card-grid">
<div class="card">Item 1</div>
<div class="card">Item 2</div>
<div class="card">Item 3</div>
<div class="card">Item 4</div>
<div class="card">Item 5</div>
<div class="card">Item 6</div>
</div>
*/
How it works: This snippet demonstrates how to create a highly responsive grid layout without using media queries. The `grid-template-columns: repeat(auto-fit, minmax(250px, 1fr))` property ensures that grid items (cards) will automatically fit into the available space. Each card will be at least `250px` wide, but can shrink or grow to take up an equal share (`1fr`) of the remaining space, adding or removing columns as the viewport resizes. The `gap` property provides spacing between grid items.