stroibot
stroibot

Reputation: 878

Synchronize CSS Animation

is there any possibility to synchronize CSS Animation? E.g.,

I have this animation:

@keyframes AnimatedGradient {
    0% {
        background-position: 0% 50%
    }
    50% {
        background-position: 100% 50%
    }
    100% {
        background-position: 0% 50%
    }
}

And I apply it with this class to any element that I want:

.animated-gradient {
    background: linear-gradient(270deg, #FC5C7D, #6A82FB, #EB3349, #F45C43, #FF8008, #FFC837, #4CB8C4, #3CD3AD, #24C6DC, #514A9D, #FF512F, #DD2476, #DA22FF, #9733EE, #22c1c3, #fdbb2d);
    background-size: 3200% 3200%;
    animation: AnimatedGradient 160s linear infinite;
}

If I apply it to the 2 or more elements, e.g., the first one is background (body tag) and the other one is button on hover, so when I hover on it the animation is starting from the start, but I want it to be synchronized with the background. So how can I do that? Preferably using plain JavaScript. Thanks!

Upvotes: 3

Views: 1306

Answers (1)

Prasad Kothavale
Prasad Kothavale

Reputation: 444

Maybe you can make the background of button transparent on hover. Below snippet might help. In the snippet, I have given a thick border to the button to make the button visible while hovering but you can use different techniques (like clipping or stack button in between divs) which is suitable as per your code.

@keyframes AnimatedGradient {
    0% {
        background-position: 0% 50%
    }
    50% {
        background-position: 100% 50%
    }
    100% {
        background-position: 0% 50%
    }
}

.animated-gradient {
    background: linear-gradient(270deg, #FC5C7D, #6A82FB, #EB3349, #F45C43, #FF8008, #FFC837, #4CB8C4, #3CD3AD, #24C6DC, #514A9D, #FF512F, #DD2476, #DA22FF, #9733EE, #22c1c3, #fdbb2d);
    background-size: 3200% 3200%;
    animation: AnimatedGradient 160s linear infinite;
}

body {
  text-align: center;
  margin: 0;
  padding: 0;
}

.btn {
  background-color: #000;
  color: #fff;
  padding: 10px;
  transition-duration: 0.4s;
  transition-timing-function: ease;
  border-top: solid 25px #fff;
  border-bottom: solid 25px #fff;
  border-left: solid 150px #fff;
  border-right: solid 150px #fff;
  margin-top: 50px;
}

.btn:hover {
  background-color: transparent;
  color: #fff;
  transition-duration: 0.4s;
  transition-timing-function: ease;
}
<html>
<body class="animated-gradient">
  <div>
    <button class="btn">Hover Me!</button>
  </div>
</body>
</html>

Upvotes: 3

Related Questions