CSS
CSS Grid: Responsive Auto-Fit Columns with `minmax()`
Create dynamic, responsive grid layouts with auto-fitting columns that adjust effortlessly using `repeat(auto-fit, minmax(width, 1fr))`.
.grid-gallery {
display: grid;
/* auto-fit will create as many columns as fit the available space.
minmax(250px, 1fr) ensures each column is at least 250px wide,
but will grow to fill available space evenly (1fr). */
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
padding: 20px;
background-color: #f8f9fa;
max-width: 1200px; /* Example max-width for the gallery */
margin: 0 auto; /* Center the gallery */
}
.grid-item {
background-color: #ffffff;
border: 1px solid #dee2e6;
border-radius: 8px;
padding: 20px;
text-align: center;
box-shadow: 0 4px 6px rgba(0,0,0,0.05);
font-size: 1.2em;
font-weight: bold;
color: #343a40;
}
.grid-item img {
max-width: 100%;
height: auto;
border-radius: 4px;
margin-bottom: 15px;
}
<!-- HTML -->
<div class="grid-gallery">
<div class="grid-item">
<img src="https://via.placeholder.com/250x150?text=Item+1" alt="Item 1">
<span>Grid Item 1</span>
</div>
<div class="grid-item">
<img src="https://via.placeholder.com/250x150?text=Item+2" alt="Item 2">
<span>Grid Item 2</span>
</div>
<div class="grid-item">
<img src="https://via.placeholder.com/250x150?text=Item+3" alt="Item 3">
<span>Grid Item 3</span>
</div>
<div class="grid-item">
<img src="https://via.placeholder.com/250x150?text=Item+4" alt="Item 4">
<span>Grid Item 4</span>
</div>
<div class="grid-item">
<img src="https://via.placeholder.com/250x150?text=Item+5" alt="Item 5">
<span>Grid Item 5</span>
</div>
<div class="grid-item">
<img src="https://via.placeholder.com/250x150?text=Item+6" alt="Item 6">
<span>Grid Item 6</span>
</div>
</div>
How it works: This snippet showcases a powerful CSS Grid technique for creating responsive, auto-fitting columns. By using `grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));`, the grid automatically creates as many columns as can fit into the available space. Each column will be at least `250px` wide, but will expand or shrink to fill the remaining space equally (`1fr`), eliminating the need for complex media queries to adjust column counts. This is ideal for image galleries or product listings where item count is dynamic.