Search code examples
csscss-animationssequential

Css sequential animation messed up


I want to achive a sequential css animation, where a div moves around the borders of another div. Two of the directions work (down to up and right to left) works, the others seem to get mixed up.

The code I have is

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -ms-box-sizing: border-box;
}
body {
  background: #000;
}
.box-outer {
  overflow: hidden;
  margin: 50px auto;
  width: 200px;
  height: 200px;
}
.main_box {
  width: 200px;
  height: 200px;
  position: relative;
  background: #f34c4c;
  border: 10px solid #000;
}
.bar {
  position: absolute;
  width: 10px;
  height: 10px;
  background: #fff;
  top: -10px;
  left: -10px;
  animation-name: move-right, move-down, move-left, move-up;
  animation-delay: 0, 2s, 4s, 6s;
  animation-duration: 2s, 2s, 2s, 2s;
  animation-iteration-count: infinite, infinite, infinite, infinite;
}

@keyframes move-right {
  0% {
    left: -10px;
  }
  25% {
    left: 100%;
  }
}
@keyframes move-down {
  26% {
    top: -10px;
  }
  50% {
    top: 100%;
  }
}
@keyframes move-left {
  51% {
    left: 100%;
  }
  75% {
    left: -10px;
  }
}
@keyframes move-up {
  76% {
    top: 100%;
  }
  99% {
    top: -10px;
  }
}
<div class="box-outer">
  <div class="main_box">
    <div class="bar"></div>
  </div>
</div>


Solution

  • This is because you have to set both top and left values in each of your Keyframes.
    By the way, you could use a single animation, not 4.

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
      -ms-box-sizing: border-box;
    }
    
    body {
      background: #000;
    }
    
    .box-outer {
      overflow: hidden;
      margin: 50px auto;
      width: 220px;
      height: 220px;
    }
    
    .main_box {
      width: 220px;
      height: 220px;
      position: relative;
      background: #f34c4c;
      border: 10px solid #000;
    }
    
    .bar {
      position: absolute;
      width: 10px;
      height: 10px;
      background: #fff;
    }
    
    .top {
      top: -10px;
      left: -10px;
      animation: move 4s infinite linear;
    }
    
    @keyframes move {
      0% {
        top: -10px;
        left: -10px;
      }
      25% {
        top: -10px;
        left: 200px;
      }
      50% {
        top: 200px;
        left: 200px;
      }
      75% {
        top: 200px;
        left: -10px;
      }
    }
    <div class="box-outer">
      <div class="main_box">
        <div class="bar top"></div>
      </div>
    </div>