A CSS image gallery organizes collections of photo thumbnails into responsive grids using CSS Grid or Flexbox, complete with hover scaling, captions, and card borders.
Responsive galleries use CSS Grid repeat(auto-fill, minmax(...)) for multi-column adaptation:
.gallery-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 1.5rem;
}
.gallery-card {
background-color: #1e293b;
border-radius: 8px;
overflow: hidden;
transition: transform 0.3s ease;
}
.gallery-card:hover {
transform: translateY(-4px);
}
.gallery-card img {
width: 100%;
height: 180px;
object-fit: cover; /* Prevents image stretching distortion */
}
Key gallery features:
auto-fill: Automatically calculates how many gallery columns fit on screen.object-fit: cover: Crops images neatly to fit card aspect ratios without distortion.transform: translateY(-4px)) on mouse hover.flowchart TD
A["Grid Container (minmax(220px, 1fr))"] --> B["Mobile Viewport: 1 Column Grid"]
A --> C["Tablet Viewport: 2-3 Column Grid"]
A --> D["Desktop Viewport: 4-5 Column Grid"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Image Gallery Example</title>
<style>
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 1.5rem;
}
.photo-card {
background-color: #1e293b;
border-radius: 8px;
overflow: hidden;
border: 1px solid #334155;
transition: transform 0.3s ease;
}
.photo-card:hover {
transform: translateY(-4px);
}
.photo-card img {
width: 100%;
height: 160px;
object-fit: cover;
display: block;
}
.caption {
padding: 10px;
font-size: 0.9rem;
color: #94a3b8;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 2rem;">
<h2>Responsive Photo Gallery Grid</h2>
<div class="gallery">
<div class="photo-card">
<img src="https://images.unsplash.com/photo-1498050108023-c5249f4df085" alt="Workspace">
<div class="caption">Developer Workspace</div>
</div>
<div class="photo-card">
<img src="https://images.unsplash.com/photo-1518770660439-4636190af475" alt="Hardware">
<div class="caption">Tech Setup</div>
</div>
</div>
</body>
</html>
object-fit: cover on gallery thumbnail images: Prevents photos with different aspect ratios from stretching or warping.grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)): Eliminates media query code by letting CSS Grid handle responsive columns automatically.overflow: hidden to .photo-card containers: Ensures zoomed images remain clipped inside rounded card borders.Create a CSS class .gallery using CSS Grid with gap: 1rem; and grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.