Search code examples
htmlcsscss-animationscss-transforms

Basic Animation HTML and CSS


So I am just a beginner and I am just trying to figure out animations and how they work.

My plan is to move the ball infinitenly in an infinite number of degrees (lets say 90) on a line. Here are a couple of problems I wondered:

  1. Is there a better way to use classes that have common and slightly different rules (having different rotations) ?
  2. How can I have the ball movement on the new lines having different rotations?

.line,
.line-deg90 {
  background-color: hsl(0, 0%, 0%);
  height: 3px;
  width: 400px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin: 0 0 0 -200px;
  transform-origin: 50%;
}

.line-deg90 {
  transform: rotate(90deg);
}

.ball {
  background-color: hsl(0, 0%, 0%);
  height: 30px;
  width: 30px;
  border-radius: 50%;
  position: absolute;
  top: -15px;
  left: 0;
  animation: move 2s infinite alternate ease-in-out;
}

@keyframes move {
  0% {
    left: 0px;
    top: -15px;
  }

  100% {
    left: 370px;
    top: -15px;
  }
<div class="line">
  <div class="ball"></div>
<div class="line-deg90"></div>


Solution

  • Here is an idea using CSS variables to have a generic code. Simply adjust the angle and the offset to control the movement

    .ball {
      --angle: 0deg;
      --offset: 150px;
      
      background-color: hsl(0, 0%, 0%);
      height: 30px;
      width: 30px;
      border-radius: 50%;
      position: absolute;
      inset: 0;
      margin: auto;
      animation: move 2s infinite alternate ease-in-out;
    }
    
    @keyframes move {
      0% {
        transform: rotate(var(--angle)) translate(var(--offset))
      }
      100% {
        transform: rotate(var(--angle)) translate(calc(-1*var(--offset)))
      }
    }
    
    
    html {
      min-height:100%;
      background:
        linear-gradient(red 0 0) center/100% 2px,
        linear-gradient(red 0 0) center/2px 100%;
      background-repeat:no-repeat;
    }
    <div class="ball"></div>
    <div class="ball" style="--angle:90deg;--offset:100px"></div>