Search code examples
htmlcsscss-animationsslideshowkeyframe

Why is the background flashing/flickering when transitioning to another image? css animation keyframes


The background is supposed to be a automatic slideshow of different images. However, when it transitions to the next image, there is a white flash/flick. Am I doing something wrong? I'm using keyframes in css

html,body{
  animation-name: rainbowtext;
  animation-duration: 35s;
  animation-timing-function: ease-in;
  animation-iteration-count: infinite;
}


@keyframes rainbowtext{
  0%{
    background-image: url("diet-soda.jpg");
    background-size: cover;
    background-repeat: no-repeat;
    height: 100%;
  }
  25%{
    background-image: url("coke.jpeg");
    background-size: cover;
    background-repeat: no-repeat;
    height: 100%;
  }
  50%{
    background-image: url("diet-soda2.jpg");
    background-size: cover;
    background-repeat: no-repeat;
    height: 100%;
  }
  75%{
    background-image: url("soda2.jpg");
    background-size: cover;
    background-repeat: no-repeat;
    height: 100%;
  }
  100%{
    background-image: url("sugar.jpeg");
    background-size: cover;
    background-repeat: no-repeat;
    height: 100%;
  }
}

Solution

  • As Temani Afif already said, your problem comes from the loading time from the server.

    Preload your images using them for the previous keyframe, even though they aren't visible:

    html,body{
      animation-name: rainbowtext;
      animation-duration: 35s;
      animation-timing-function: ease-in;
      animation-iteration-count: infinite;
        background-size: cover;
        background-repeat: no-repeat;
        height: 100%;
    }
    
    
    @keyframes rainbowtext{
      0%{
        background-image: url("diet-soda.jpg"), url("coke.jpeg");
      }
      25%{
        background-image: url("coke.jpeg"), url("diet-soda2.jpg");
      }
      50%{
        background-image: url("diet-soda2.jpg"), url("soda2.jpg");
      }
      75%{
        background-image: url("soda2.jpg"), url("sugar.jpeg");
      }
      100%{
        background-image: url("sugar.jpeg");
      }
    }