DEV Community

Cover image for πŸ“· I created an infinite photo grid using only HTML & CSS
Max Mykhalchuk
Max Mykhalchuk

Posted on

πŸ“· I created an infinite photo grid using only HTML & CSS

Recently, I decided to create an infinite photo grid.

There were 2 options to go with: creating an actual CSS grid with img tags all around or using a "collage" with photos (which is easier but doesn't really change the implementation).

I can't remember which option I decided to choose though...

Monkey Puppet Meme
So, anyway, here's the result:

Implementation

The implementation is pretty much simple.

We have a single HTML element:



<main class="infinite-photo-grid"></main>


Enter fullscreen mode Exit fullscreen mode

And a bit of CSS:



.infinite-photo-grid {
  width: 100%;
  height: 100%;
  max-height: 750px;
  background-image: url(https://raw.githubusercontent.com/s1mpson/-/master/codepen/infinite-photo-grid/photo-grid.jpg);
  background-size: calc(4.84 * min(100vh, 750px)) min(100vh, 750px);
  background-repeat: repeat-x;
  animation: scroll 50s linear infinite;
}

@keyframes scroll {
  from {
    background-position: left calc(4.84 * min(100vh, 750px)) top 0px;
  }
  to {
    background-position: left 0px top 0px;
  }
}


Enter fullscreen mode Exit fullscreen mode

So, the basic idea - is having a repeated background image on the X-axis that is being scrolled by our @keyframe function. In order not to trim the top and bottom sides of the picture, we need to know image resolution so we could calculate the ratio (in our case it's 3630Γ—750px = 4.84 ratio).

Then, we lock our background-size to window/image height and calculate the unknown parameter (width) by using a pre-calculated ratio.

For the scroll animation, we change the background-position property from the image width to 0px, so it would create a motion effect.

I hope you enjoyed this article. Feel free to check me on:

Top comments (3)

Collapse
 
dandv profile image
Dan Dascalescu

Nice hack! Is this a proper photo grid (multiple images), or a scrolling background image more precisely?

Collapse
 
s1mpson profile image
Max Mykhalchuk

Thanks :) This one is a scrolling background image, that looks like photo grid. But I'm already planning to make an "Infinite Photo Grid v2.0" with a proper CSS grid and multiple images & gonna show the difference between them

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€

This 2nd version would be better for accessibility and performance. The difference will be along the lines of, background position cannot be rendered GPU but transform 3d can, I can see this version may have some scroll jank issues. You can also add will-change for buttery smooth transition.