Will
Will

Reputation: 307

Animate element without animating pseudo-elements

I have a div and both ::before and ::after pseudo-elements of this div. I want to animate each one of them with different delays(0, 0.5s and 1.0).

I have tried in many ways until I realized I could move both pseudo-elements with the delay I wanted, but not the div itself or I could move only the div and the pseudo-elements would move in the same timing.

In the second case, if I try to animate the pseudo-elements separately, they do the animation twice.

First example:

.wave {
  background-color: blue;
  border-radius: 50%;
  height: 26px;
  margin: auto;
  position: relative;
  width: 26px;
}

.wave:before, .wave:after {
  animation: bounce 1s linear infinite alternate;
  border-radius: inherit;
  content: ' ';
  height: inherit;
  margin: inherit;
  position: absolute;
  width: inherit;
}

.wave:before {
  background-color: red;
  right: 30px;
}

.wave:after {
  background-color: green;
  animation-delay: 1s;
  left: 30px;
}

Seconde example:

.wave {
  animation: bounce 1s linear infinite alternate;
  background-color: blue;
  border-radius: 50%;
  height: 26px;
  margin: auto;
  position: relative;
  width: 26px;
}

.wave:before, .wave:after {
  border-radius: inherit;
  content: ' ';
  height: inherit;
  margin: inherit;
  position: absolute;
  width: inherit;
}

.wave:before {
  background-color: red;
 right: 30px;
}

.wave:after {
  background-color: green;
  animation-delay: 1.2s;
  left: 30px;
}

Having said that, all I want to know is:

Is it possible to move all of them, using only one div, with different timing? How so?

EDIT 1

Here is a codepen, highlighting this case: https://codepen.io/haaswill/pen/vyroJG

Upvotes: 2

Views: 914

Answers (1)

Karol
Karol

Reputation: 54

You should be able to just put the animation property on the :before and :after

I fiddled with this heh - I was able to get the 3 parts to animate on their own. Check it out here: https://jsfiddle.net/karolbrennan/706gkbna/2/

@keyframes bounce {
    0%   {left: 0px; }
    25%  {left: 25px; }
    50%  {left: 50px; }
    75%  {left: 25px; }
    100% {left: 0px; }
}

.wave {
  animation: bounce 3.5s linear infinite alternate;
  background-color: blue;
  border-radius: 50%;
  height: 26px;
  margin: 100px auto;
  position: relative;
  width: 26px;
}

.wave:before, .wave:after {
  background-color: inherit;
  border-radius: inherit;
  content: ' ';
  height: inherit;
  width: inherit;
  position: absolute;
}

.wave:before {
  animation: bounce 1.5s linear infinite alternate;
  animation-delay: 0.25s;
  right: 30px;
}

.wave:after {
  animation: bounce 2s linear infinite alternate;
  animation-delay: 0.5s;
  left: 30px;
}

There's an article about this here: https://cssanimation.rocks/pseudo-elements/

Upvotes: 1

Related Questions