Nashie
Nashie

Reputation: 331

delaying an animation for x seconds with css

I have an element I would like to fade in and fade out but show for 10 seconds.

.element  {
-webkit-animation: fadeinout 2s linear forwards;
transition-delay: 10s;
animation: fadeinout 2s linear forwards;
opacity: 0;
}

@-webkit-keyframes fadeinout {
  50% { opacity: 1; }
}

@keyframes fadeinout {
  50% { opacity: 1; }
}

I have been trying for a while and think I have completely miss understood something.

UPDATE -----

What I'm trying to do is for the element to fade in over 2 seconds then show for 10 secs then fade out over 2 seconds.

Upvotes: 1

Views: 1045

Answers (3)

Arman Ebrahimi
Arman Ebrahimi

Reputation: 2297

transition-delay is wrong. It is about the transition. The equivalent of that is: animation-delay. use animation-duration: 14s for the time of running animation. or:

.element  {
-webkit-animation: fadeinout 14s linear forwards;
animation: fadeinout 14s linear forwards;
opacity: 0;
width: 100px;
height: 100px;
background-color: red;
}

@-webkit-keyframes fadeinout {
  14% { opacity: 1; }
  86% { opacity: 1; }
  100% { opacity: 0; }
}

@keyframes fadeinout {
  14% { opacity: 1; }
  86% { opacity: 1; }
  100% { opacity: 0; }
}
<div class="element"></div>

Upvotes: 3

A Haworth
A Haworth

Reputation: 36426

To get a 2 second fadein, a 'stay there' for 10 seconds and then a 2 second fadeout you have an overall animation time of 14 seconds.

For the first (2 / 14) * 100% [=14.29%] you want the opacity to go from 0 to 1

For the next (10 / 14) * 100% [=71.43%] you want the opacity to stay at 1

For the last (2 / 14) * 100% [=14.29%] you want the opacity to go from 1 to 0.

So the animation keyframes look like this:

@keyframes fadeinout {
  0%, 100% { opacity: 0; }
  14.29%, 85.72% { opacity: 1; }
}

You don't want a delay on your animation (animation-delay just delays the start of an animation).

Current CSS does not allow us to use a calc function in the % settings in keyframes so we've had to do the calculation in advance and build it in (it didn't seem worth going to more than a couple of decimal places).

.element {
  animation: fadeinout 14s linear forwards;
  opacity: 0;
  width: 20vmin;
  height: 20vmin;
  background-color: magenta;
}

@keyframes fadeinout {
  0%,
  100% {
    opacity: 0;
  }
  14.29%,
  85.72% {
    opacity: 1;
  }
}
<div class="element"></div>

Upvotes: 1

Dylan Manchester
Dylan Manchester

Reputation: 33

This may be a little verbose, but if it is acceptable for your fade duration to be proportional to the duration it is shown you could use a keyframe structure like this:

@keyframes fadeinout {
    0% { opacity: 0; },
    10% { opacity: 1; },
    90% { opacity: 1; },
    100% { opacity: 0; }
}

Upvotes: 1

Related Questions