0

I am making a circle shrinking and growing with the keyframes animation kit. I've gived my div a margin-left: 45vw, and margin-top: 45vh. This obviously makes the circle not being centered all of the time as the size of the circle varies. Is there anything I can add to my code so that the center of the circle always stays at the middle of the screen?

<!DOCTYPE html>
<html>
<style>

#ball {
    width: 100px;
    height: 100px;
    margin-left: 45vw;
    background-color: purple;
    border-radius: 50%;
    animation-name: sprett;
    animation-duration: 5s;
    animation-iteration-count: infinite;
}

@keyframes sprett {
    40% {
        width: 25px;
        height: 25px;
    }
    50% {
        width: 100px;
        height: 100px;
    }
    90% {
        width: 175px;
        height: 175px;
    }
    100% {
        width: 100px;
        height: 100px;
    }
}

</style>
<body>

<div id="ball"></div>

</body>
</html>
roberten
  • 23
  • 3

1 Answers1

1

For a smoother animation you would be better off using scale rather than altering height and width - it animates better but also has the added benefit that the size taken up does not change so any position you put it in to begin with remains - with the transform origin being (by default) at the center of the element you can get the look you want:

<!DOCTYPE html>
<html>
<style>
  #ball {
    width: 100px;
    height: 100px;
    margin-left: 45vw;
    background-color: purple;
    border-radius: 50%;
    animation-name: sprett;
    animation-duration: 5s;
    animation-iteration-count: infinite;
  }
  
  @keyframes sprett {
    40% {
      transform: scale(0.25);
    }
    50% {
      transform: scale(1);
    }
    90% {
      transform: scale(1.75);
    }
    100% {
      transform: scale(1);
    }
  }
</style>

<body>

  <div id="ball"></div>

</body>

</html>

However, you code does not exactly center the ball on every viewport (it mixes vw and px units). You can change the tranforms to transform: translateX(-50%) scale(...) and set left: 50vw to center the ball.

A Haworth
  • 30,908
  • 4
  • 11
  • 14