Advertisement


How to create a responsive sprite sheet animation in css?


Question

i've been trying to do this for hours but so far i haven't made any progress.

I have a site with a few animations in it, some will be activated on click and some on hover. something similar to the animation found in this site : http://www.pixelwrapped.com/ the cat tail is reponsive as in when you scale the broswer it scales along with it as well.

this is the code that i am using to create the animation

.monster {
            position: absolute;
            width: 100px;
            height: 100px;
            margin: 2% auto;
            background: url('img/le-cloud.png') left center;
            overflow: auto;
            display: block;
            left: 20%;
            top: 40%;

        }
        .monster:hover {
            position: absolute;
            width: 100px;
            height: 100px;
            margin: 2% auto;
            background: url('img/le-cloud.png') left center;
            animation: play .9s steps(18);
            overflow: auto;
            display: block;
            left: 20%;
            top: 40%;

        }

i found this tutorial which uses percentages, that works for changing 1 frame not playing the entire 18 frames in this example , i have other animations composed of more than 30 sprites, i looked into spritely.js but it wasn't responsive.

Any ideas how can i solve this ?

2014/10/22
1
1
10/22/2014 9:59:00 AM

Accepted Answer

I figured out how to do it eventually! Just in case anyone still cares, Let me do some explaning just so you don't go through what I went throught:

    <style>
      div.sprite {
            margin: 0 auto;
            width: 40%;
/*            Change this to what ever value you desire*/
            height: 0;
            padding-bottom: 40%;
            background-image: url("le-cloud-copy.png");
/*            Add the sprite sheet here, must be on a staright line*/
            background-position: 0 0;
            background-size: 1800%;
/*            I have 18 sprites in the sheet thus it's 1800%, if it was 4 you'd use 400% and so on*/
            display: block;
        }
        div.sprite:hover {
/*            background-position: 500% 0;*/
            animation: play .9s steps(18);
/*            18 steps to go over al the sprites i have, if you had 4 in the sprite the value would be 4 for example */
        }
        @keyframes play {
            100% {
                background-position: 1800% 0;
            }
        }
    </style>

And the magic bit is here include this library and this should work.

<script src="js/prefixfree.min.js"></script>
2014/10/22
1
10/22/2014 5:18:00 PM