'CSS: how to make sprite animate in the same place?
I have an animation of pixel art of a cartoon character standing still, but the animation is sliding which makes it look like the character is walking.
Outcome I want is character animating in the same place and not sliding
HTML
<nav class = "nav">
<div class = "nav-item">
<ul>
<div class = "agumon">
<img class = "agumon-standing" src="images/sprites/standing/standing-collection.png" alt="agumon sprite">
</div>
<li><a href="#"></a>Home</li>
<li><a href="#"></a>About Me</li>
<li><a href="#"></a>Experience</li>
<li><a href="#"></a>Work</li>
<li><a href="#"></a>Contact</li>
</ul>
</div>
</nav>
CSS
.agumon{
position: absolute;
width: calc(22px * var(--pixel-size));
height: calc(32px * var(--pixel-size));
overflow: hidden;
margin-left:41rem;
display: none;
}
.agumon-standing{
animation: movespritesheet 2s steps(12) infinite;
width: calc(320px * var(--pixel-size));
image-rendering: pixelated;
}
@keyframes movespritesheet {
from{
transform: translate3d(0px, 0, 0);
}
to{
transform: translate3d(-100%, 0, 0);
}
}
I have attached the image I am using so you can see how it is animating
Solution 1:[1]
It seems there is an issue with your sprite. Better define a clear size of each image to get a clear aspect-ratio
The below code show the issue with your image and gives you the code that should work fine. The ratio is around 0.77 which produce the bad effect du to rounding. Try to produce a ratio equal to 1
.box {
width: 50px; /* control the size here */
aspect-ratio: 0.77; /* the ratio of on sprite */
overflow: hidden;
}
.box img {
display: block;
height: 100%;
animation: movespritesheet 2s steps(12) infinite;
}
@keyframes movespritesheet {
to{transform: translate(-100%)}
}
/* to debug */
.container {
--s: 50px;
height:calc(var(--s)/0.77);
width: calc(12*var(--s));
outline:2px solid red;
background:
repeating-linear-gradient(90deg,#0000 0 calc(var(--s) - 2px),red 0 var(--s)),
url(https://i.stack.imgur.com/PyXSG.png) 0/auto 100% no-repeat;
}
<div class="container"></div>
<div class="box">
<img src="https://i.stack.imgur.com/PyXSG.png" >
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Temani Afif |

