How to prevent CSS @keyframes from reverting to the start

Back to blog

I recently had to add an overlay to an image.

 

I created an overlay div, with a black background.  Inside this div is an image which the client could change the opacity using a sliding scale.

 

Overlay

The issue I had was that the images were being lazy loaded, and all transitioned onto the screen after a 0.6s delay.  This meant that the overlay with its black background would display as a black square for 0.6 seconds before the images loaded. Not ideal.

 

I decided to use a keyframe to add a delay on the overlay loading onto the page.

 

A fade in of colour can easily be achieved by using the @keyframes rule.

 

CSS

div {
  width: 200px;
  height: 200px;
  background-color: #fff;
  animation-name: fadein;
  animation-duration: 4s;
}

@keyframes fadein {
  from {background-color: #fff;}
  to {background-color: #000;}
}
   

(click on Result to re-run the animation below)

The problem:

  • after the transition is complete it goes back to the original colour: white
  • I don't actually need a transition at all, I just want a delay. After 0.6s load the black background.

 

The key to achieve this, is to set the background to white for 99% of the transition & black for the remaining 1%.

 

div {
  width: 200px;
  height: 200px;
  background-color: #fff;
  animation: fadein 3s forwards;
 
}

@keyframes fadein {
       99% {
            background-color:#fff;
        }
        100%{
            background-color:#000;
        }
}

I've added a 3 second delay to the code below.

 

(click on Result to re-run the animation below)

 

Darren Welch

By

Darren Welch


  13 July 2020


Contact me online

Advertisment


Has this helped?


If this has saved you time and you are feeling generous, why not buy me a coffee.

Thank You cup of coffee

Comment