Sasgorilla
Sasgorilla

Reputation: 3130

How can I compose multiple CSS animations/properties that all use transform?

Say I have a spinning animation that looks like this:

@keyframes spinning {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

I can use it like this:

.spinning {
  animation: spinning 1s infinite;
}

I also have a "skewing" animation:

@keyframes skewing {
  0% {
    transform: skew(0deg);
  }
  25% {
    transform: skew(40deg);
  }
  50% {
    transform: skew(0deg);
  }
  75% {
    transform: skew(-40deg);
  }
  100% {
    transform: skew(0deg);
  }
}

How can I apply those two animations to the same element? Since they both use transform, they trample on each other, and on any other static transform property I try to include:

.fun {  // doesn't work - pick one of three :(
  animation: spinning 1s infinite;
  animation: skewing 1s infinite;
  &:hover {
    transform: scale(2.0)
  }
}

See CSS playground example.

I realize I can combine all the transforms by hand into one big mega-keyframes -- but then I've lost the usefulness of having reusable, composable animations. Is it possible to compose these somehow?

Upvotes: 0

Views: 32

Answers (1)

Temani Afif
Temani Afif

Reputation: 273838

by using animation-composition

body {
  background: #6e28d9;
  padding: 0 24px;
  color: white;
  margin: 0;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

@keyframes spinning {
  100% {
    transform: rotate(360deg);
  }
}

@keyframes skewing {
  25% {
    transform: skew(40deg);
  }
  50% {
    transform: skew(0deg);
  }
  75% {
    transform: skew(-40deg);
  }
}

.fun {
  animation: 
    skewing 1s infinite,
    spinning 1s infinite;
  animation-composition: add;
  &:hover {
    transform: scale(2) skew(10deg);
  }
}
<div class="fun">wheeeee</div>

Or individual transform properties by updating the rotation for example:

body {
  background: #6e28d9;
  padding: 0 24px;
  color: white;
  margin: 0;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

@keyframes spinning {
  100% {
    rotate: 360deg;
  }
}

@keyframes skewing {
  25% {
    transform: skew(40deg);
  }
  50% {
    transform: skew(0deg);
  }
  75% {
    transform: skew(-40deg);
  }
}

.fun {
  animation: 
    skewing 1s infinite,
    spinning 1s infinite;
  &:hover {
    transform: scale(2) skew(10deg);
  }
}
<div class="fun">wheeeee</div>

Upvotes: 3

Related Questions