Home > Mobile >  Match absolute left with max-width in animation
Match absolute left with max-width in animation

Time:07-04

I'm making a worm, the worm moves from position A to B. The goal is to have the "body" of the worm stretch up to position B, and the "tail" gets contracted after it reaches B.

Currently, I'm expanding the max-width of the worm and then moving the absolute left position to the exact amount I expanded the worm. So, if the worm expanded 20vw, the absolute left of the whole worm after is contracted becomes 20vw.

I'm having difficulties trying to figure out how to 'hold' position B while contracting the tail of the worm. I'm able to expand and contract the body at the same time, but I want to separate these two movements. Only after the head reaches position B, the tail gets contracted.

Code: enter image description here enter image description here enter image description here

CodePudding user response:

The left and right CSS properties are animatable so we can use them to initially fix the left and move the right and then fix the right and move the left rather than animate the max-width.

.worm {
  position: absolute;
  top: 30px;
  left: 50px;
  right: calc(50px   100px);
  height: 100px;
  background-color: aquamarine;
  border-radius: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  animation: move-worm 3s ease-in-out;
  animation-fill-mode: forwards;
}

@keyframes move-worm {
  0% {
    left: 50px;
    right: calc(100vw - 50px - 100px);
  }
  50% {
    left: 50px;
    right: calc(100vw - 50px - 100px - 20vw);
  }
  100% {
    left: calc(20vw   50px);
    right: calc(100vw - 50px - 100px - 20vw)
  }
}
<div class='worm'>
  <div class='worm-eye'>
    <div class='worm-lid' />
    <div class='worm-iris'>
      <div class='worm-iris-container'>
        <div class='worm-iris-glow' />
      </div>
    </div>
  </div>
</div>

  • Related