SyntaxStudy
Sign Up
html

How to Create a Responsive Image Gallery

Build a responsive photo gallery using CSS Grid without any JavaScript.

CSS Grid makes building responsive galleries trivial. Use auto-fill with minmax() for automatic column adjustment.

auto-fill vs auto-fit

  • auto-fill — fills the row with as many columns as possible, even if empty
  • auto-fit — same but collapses empty columns, stretching existing items

Adding Lightbox

Use the <dialog> element or a CSS-only :target trick for a lightbox without JavaScript.

Example
<!-- HTML -->
<div class="gallery">
  <img src="photo1.jpg" alt="Photo 1">
  <img src="photo2.jpg" alt="Photo 2">
  <img src="photo3.jpg" alt="Photo 3">
  <img src="photo4.jpg" alt="Photo 4">
  <img src="photo5.jpg" alt="Photo 5">
</div>

<!-- CSS -->
.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 1rem;
}

.gallery img {
  width: 100%;
  aspect-ratio: 1 / 1;
  object-fit: cover;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.gallery img:hover {
  transform: scale(1.03);
  box-shadow: 0 8px 24px rgba(0,0,0,0.2);
}