csscss-animationsbackground-imagebackground-position

Looped background animation without setting px position


I have been using a preprocessor to generate looped background animation like this:

@keyframes anim
{
    from    {   background-position: 0 0;               }
    to      {   background-position: 256px 256px;       }
}

div
{
    background-image: url('256.png');
    width: 256px;
    height: 256px;
    background-size: 256px 256px;
    background-repeat: repeat;
    animation: anim 5s linear infinite;
}

…where 256px 256px in background-position are extracted from the image (256.png) by the preprocessor.

I'm curious, can it be done in pure CSS without setting image-dependent px values in background-position? As far as I understand, I can't use percentage for background-position while the container and the image are both the same size.


Solution

  • Use a pseudo element and it will be even better for performance as well:

    div {
      background-image: url(https://picsum.photos/id/1069/300/300);
      width: 200px;
      height: 200px;
      position: relative;
      overflow: hidden;
    }
    div:before {
      content:"";
      position: absolute;
      inset: -100% 0 0 -100%;
      background: inherit;
      background-size: 50% 50%;
      animation: anim 5s linear infinite;
    }
    @keyframes anim {
      to {
        translate: 50% 50%;
      }
    }
    <div></div>
    <br>
    <div style="width: 100px;height: 100px;"></div>