cssweb-frontendreact-animations

CSS animation for both spinning and moving a ball simultaneously


I have a simple react app with a div containing an SVG ball image. Upon hovering on the image, I want it to rotate and move left simultaneously smoothly. When hover state is false, I want it to rotate and roll back to its initial position.

I'm struggling to combine both effects in CSS.

BallRoll.js

 <div className="ball-holder">
              <img
                src={rollingBall}
                loading="lazy"
                width="223"
                alt="rolling Ball"
                className="ball"
              />
   </div>

I'm a bit lost on the css, can't figure out a proper way to combine everything. ball.css

.ball {
 display: block;
transition: 1s ease-in-out;
}

.ball:hover {
animation: animate2 5s linear; 
}
 @keyframes animate2 {
    0%{
        transform: rotate(0deg);
        left:0;
    }
    50%{
        transform: rotate(360deg);
        left:calc(100% - 50px);
    }
    100%{
        transform: rotate(0deg);
        left:0;
    }

They are not perfect, work fine individually, but not together. Any better suggestions and help?


Solution

  • Here is a working example.

    One thing to note is that if you apply the affect only on hover of the ball, then as soon as the ball moves the hover will end and it will go back to non-hover state, causing just a quick flicker. For that reason I activate the animation when the ball holder is hovered.

    .ball {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      background: linear-gradient(teal, #000);
    }
    
    .ball {
      display: block;
      transition: all 2s;
    }
    
    .ball-holder:hover .ball {
      transform: translateX(calc(100vw - 80px)) rotate(360deg);
    }
    <div class="ball-holder">
      <div class="ball"></div>
    </div>