CSS animation with delay and opacity
I had a similar problem, where the requirement was to wait n
seconds before fading in different page elements, one after another.
The key to getting this working for me, that isn't mentioned in any of the other answers, is the fact that animation
can actually take a list of animations to run. It will start running them simultaneously so you need to insert delays in order to run them sequentially.
My solution was this (in SCSS, but simple enough to write as straight CSS if you need):
@mixin fade-in($waitTime) {
animation:
wait #{$waitTime},
fade-in 800ms #{$waitTime};
}
@keyframes wait {
0% { opacity: 0; }
100% { opacity: 0; }
}
@keyframes fade-in {
0% { opacity: 0; }
100% { opacity: 1; }
}
Usage:
h1 {
@include fade-in('500ms');
}
h2 {
@include fade-in('700ms');
}
I'd suggest that you set the opacity
of the element to 1 per default (for browsers that do not support animations). Then start the animation at 0s and use the keyframes to delay the animation.
#element{
animation:3s ease 0s normal forwards 1 fadein;
-webkit-animation:3s ease 0s normal forwards 1 fadein;
opacity:1
}
@keyframes fadein{
0%{opacity:0}
80%{opacity:0}
100%{opacity:1}
}
@-webkit-keyframes fadein{
0%{opacity:0}
80%{opacity:0}
100%{opacity:1}
}
http://jsfiddle.net/mg00t86v/2/
Just don't set the initial opacity
on the element itself, set it within the @keyframes
:
#element{
-webkit-animation: 3s ease 0s normal forwards 1 fadein;
animation: 3s ease 0s normal forwards 1 fadein;
}
@keyframes fadein{
0% { opacity:0; }
66% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes fadein{
0% { opacity:0; }
66% { opacity:0; }
100% { opacity:1; }
}
This technique takes the delay off of the animation, so that it starts running immediately. However, the opacity won't really change until about 66% into the animation. Because the animation runs for 3 seconds, it gives the effect of a delay for 2 seconds and fade in for 1 second.
See working example here: https://jsfiddle.net/75mhnaLt/
You might also want to look at using conditional comments for older browsers; IE8 and IE9.
Something like the following in your HTML:
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en-GB"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8 ie-7" lang="en-GB"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9 ie-8" lang="en-GB"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en-GB"> <!--<![endif]-->
You could then do something like:
.lt-ie9 #element {
opacity: 1;
}