Image Gallery in CSS
?? Creating an Image Gallery in CSS
An image gallery displays multiple images in a clean, organized layout. You can create responsive galleries using CSS Grid or Flexbox.
Example: Responsive Image Gallery Using CSS Grid
HTML
<div class="gallery"> <img src="image1.jpg" alt="Image 1" /> <img src="image2.jpg" alt="Image 2" /> <img src="image3.jpg" alt="Image 3" /> <img src="image4.jpg" alt="Image 4" /> <img src="image5.jpg" alt="Image 5" /> <img src="image6.jpg" alt="Image 6" /></div>CSS
.gallery { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; padding: 10px;}.gallery img { width: 100%; height: auto; display: block; border-radius: 8px; object-fit: cover; cursor: pointer; transition: transform 0.3s ease, box-shadow 0.3s ease;}.gallery img:hover { transform: scale(1.05); box-shadow: 0 4px 15px rgba(0,0,0,0.3);}How This Works:
display: grid;— sets the gallery container as a grid.grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));— automatically creates as many columns as fit, minimum width 150px each.gap: 10px;— space between images.Images take full width of their grid cell with
width: 100%.object-fit: cover;— makes sure images fill the grid cell nicely without distortion.Hover effect enlarges image slightly with shadow.
Alternative: Using Flexbox
.gallery { display: flex; flex-wrap: wrap; gap: 10px; padding: 10px;}.gallery img { flex: 1 1 150px; /* grow, shrink, basis */ max-width: 100%; border-radius: 8px; cursor: pointer; transition: transform 0.3s ease;}.gallery img:hover { transform: scale(1.05);}