CSS
Responsive CSS Grid Image Gallery with Auto-Fit
Build a responsive image gallery using CSS Grid's `repeat(auto-fit, minmax())` function to automatically adjust column counts based on screen size, ensuring a fluid layout.
.grid-gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
padding: 20px;
max-width: 1200px;
margin: 0 auto;
}
.grid-gallery-item {
border: 1px solid #ddd;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.grid-gallery-item img {
width: 100%;
height: 200px; /* Fixed height for uniformity */
object-fit: cover;
display: block;
}
.grid-gallery-item-info {
padding: 15px;
background-color: #f9f9f9;
}
.grid-gallery-item-info h3 {
margin-top: 0;
font-size: 1.2em;
color: #333;
}
.grid-gallery-item-info p {
font-size: 0.9em;
color: #666;
}
How it works: This CSS Grid snippet creates a responsive image gallery. The `.grid-gallery` container uses `display: grid` and `grid-template-columns: repeat(auto-fit, minmax(250px, 1fr))`. This powerful combination automatically creates as many columns as can fit, each being at least `250px` wide and shrinking or growing to fill the available space. The `gap` property provides spacing between grid items, ensuring a clean layout across different screen sizes.