Search code examples
cssanimationkeyframe

CSS Animate fails with multiple frames


This jsfiddle shows two divs using animation. The first changes as I want. The second doesn't. The difference is that the 100% keyframe is added in the second. I added it because of this note on W3Schools

Tip: For best browser support, you should always define both the 0% and the 100% selectors.

Here's the code I'm using. How do I code this so that the animation appears as shown in the top one?

    <style>
    .rotateOne {
      background-color:yellow;
      animation: rotateOneFrames 2s;
    }   
    @keyframes rotateOneFrames {
      0% {transform: rotate(360deg) scale(-1, 1); }
    }

    .rotateTwo {
      animation: rotateTwoFrames 2s;
    }   
    @keyframes rotateTwoFrames {
      0% {transform: rotate(360deg) scale(-1, 1); }
      100% {transform: rotate(360deg) scale(-1, 1); }   
    }
    </style>

    <div style="width:150px;">
      <div class="rotateOne">
        <div>Line 1</div>
        <div>Line 2</div>
        <div>Line 2</div>
      </div>
      <div class="rotateTwo">
        <div>Line 1</div>
        <div>Line 2</div>
        <div>Line 2</div>
      </div>
    </div>

Solution

  • If both, your 0% and 100% values are exactly the same, it will remain static. Solve it by setting the opposite values to the 100%:

    .rotateOne {
      background-color:yellow;
      animation: rotateOneFrames 2s;
    }   
    @keyframes rotateOneFrames {
      0% {transform: rotate(360deg) scale(-1, 1); }
    }
    
    .rotateTwo {
      animation: rotateTwoFrames 2s;
    }   
    @keyframes rotateTwoFrames {
      0% {transform: rotate(360deg) scale(-1, 1); }
      100% {transform: rotate(-360deg) scale(1, 1); } /* opposite values to the initial ones */   
    }
    <div style="width:150px;">
      <div class="rotateOne">
        <div>Line 1</div>
        <div>Line 2</div>
        <div>Line 2</div>
      </div>
      <div class="rotateTwo">
        <div>Line 1</div>
        <div>Line 2</div>
        <div>Line 2</div>
      </div>
    </div>