How can I combine spin and floating animation with CSS?
I have the code to make it float, But when I combine the code of both it doesn’t work!
CODEPEN:
HTML
<div></div>
CSS
body {
padding: 50px;
}
div {
width: 100px;
height: 100px;
background-color: #0CB1C4;
animation-name: spin;
animation-duration: 5000ms;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@keyframes spin {
from {
transform:rotate(0deg);
}
to {
transform:rotate(360deg);
}
}
/* Float */
animation-name: floating;
animation-duration: 3s;
animation-iteration-count: infinite;
animation-timing-function: ease-in-out;
@keyframes floating {
from { transform: translate(0, 0px); }
65% { transform: translate(0, 45px); }
to { transform: translate(0, -0px); }
}
lasjorg
September 19, 2022, 10:29pm
2
transform functions have to be chained. You need to either combine the two animations or use the new (ish) independent transform properties.
body {
padding: 50px;
}
div {
width: 100px;
height: 100px;
background-color: #0CB1C4;
animation-name: spin, floating;
animation-duration: 5000ms;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@keyframes spin {
from {
rotate: 0deg;
}
to {
rotate: 360deg;
}
}
@keyframes floating {
from {
translate: 0 0px;
}
65% {
translate: 0 45px;
}
to {
translate: 0 -0px;
}
}
Edit: in case you need multiple animation property
you can change your animation as you like by using this property. First start with the @keyframes rule followed by name of the animation (In this case, it is “floating”). Inside the @keyframes , you can see 3 percentage values have been declared. It is followed by a code snippet containing properties and their values.
lasjorg
September 19, 2022, 11:01pm
4
Not sure what you mean?
The transform functions will overwrite each other. Whatever animation is last in the list will overwrite the other animations transform function.
It is for the same reason this doesn’t work. The rotation will be lost when the scale is applied.
div {
width: 100px;
height: 100px;
background-color: #0CB1C4;
transform: rotate(45deg);
}
div:hover {
transform: scale(1.2);
}
Compared to this, which does retain the rotation.
div {
width: 100px;
height: 100px;
background-color: #0CB1C4;
transform: rotate(45deg);
}
div:hover {
transform: rotate(45deg) scale(1.2);
}
Or this
div {
width: 100px;
height: 100px;
background-color: #0CB1C4;
rotate: 45deg;
}
div:hover {
scale: 1.2;
}
Do you try this on the codepen? Doesn’t work.
lasjorg
September 20, 2022, 1:52pm
6
It does work. How about you show us your code?
BTW, you can’t just use the code I posted without the rest of the properties for the animation, I just did that for brevity. You need the other animation properties. I edited my post in case it isn’t clear.
system
Closed
March 22, 2023, 1:52am
7
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.