csscss-animations

Christmas Lights Loop Effect


I'm trying to create some Christmas lights (in January) using the CSS -webkit-animation property.

For this, I'm using this image:

I've tried:

@-webkit-keyframes lights {
    0% {
        background-position:0px;
    } 100% {
        background-position:0 -69px;
    }
}

#lights {
    width:100%;
    height:69px;
    background:url(https://mysterybrand.net/assets/images/new-year/live-drop-gardland.png);
    -webkit-animation: lights 1s infinite;
}

What I want to achieve: I want to constantly change the background position, so it looks like the lights are turning off and on.

For some reason, my code doesn't change the background position, and animated the image.


Solution

  • You can consider steps()1 to have the needed effect

    @keyframes lights {
        0% {
            background-position: top; 
        } 
        100% {
            background-position: bottom;
        }
    }
    
    #lights {
        height:69px;
        background:url(https://i.imgur.com/BdGY6tH.png);
        animation: lights 1s infinite steps(2,jump-none);
    }
    <div id="lights"></div>

    Or do it like this:

    @keyframes lights {
        0%,50% {
            background-position: top;
        } 
        50.1%,100% {
            background-position: bottom;
        }
    }
    
    #lights {
        height:69px;
        background:url(https://i.imgur.com/BdGY6tH.png);
        animation: lights 1s infinite;
    }
    <div id="lights"></div>

    1 More details about how to use steps() : https://stackoverflow.com/a/51843473/8620333