CSS Tutorial – Zooming Images in a Grid Layout


Creating a grid of images is easy, thanks to CSS Grid. But making the grid do fancy things after the images have been placed can be tricky to pull off.

Say you want to add some fancy hover effect to the images where they grow and zoom beyond the rows and columns where they sit? We can do that!

Cool, right? If you check the code, you won’t find any JavaScript, complex selectors, or even magic numbers. And this is only one example among many we will explore!

Now, you know all the secrets to create any kind of image grid with a cool hover effect while also having control of the sizing you want using the math we just covered.

CSS

.gallery {
  --s: 150px; /* control the size */
  --g: 10px; /* control the gap */
  --f: 1.5; /* control the scale factor */

  display: grid;
  gap: var(--g);
  width: calc(3 * var(--s) + 2 * var(--g));
  aspect-ratio: 1;
  grid-template-columns: repeat(3, auto);
}

.gallery > img {
  width: 0;
  height: 0;
  min-height: 100%;
  min-width: 100%;
  object-fit: cover;
  cursor: pointer;
  filter: grayscale(80%);
  transition: 0.35s linear;
}

.gallery img:hover {
  filter: grayscale(0);
  width: calc(var(--s) * var(--f));
  height: calc(var(--s) * var(--f));
}

body {
  margin: 0;
  min-height: 100vh;
  display: grid;
  place-content: center;
  background: #31A7FF;
}
Nandemo Webtools

Leave a Reply