CSS animation with delay and opacity

user1087110 picture user1087110 · Apr 24, 2015 · Viewed 58.2k times · Source

I am trying to fade in a element after 2 sec using CSS animation. The code works great in new browsers, but in old browsers the element will stay hidden because of "opacity:0".

I want it to be visible in old browsers and I dont want to invlove javascript. Can it be solved using CSS? Eg. some how target browsers that doesn't support animation?

CSS:

#element{
animation:1s ease 2s normal forwards 1 fadein;
-webkit-animation:1s ease 2s normal forwards 1 fadein;
opacity:0
}

@keyframes fadein{from{opacity:0}
to{opacity:1}
}

@-webkit-keyframes fadein{from{opacity:0}
to{opacity:1}
}

HTML:

<div id=element>som content</div>

Answer

Michael Giovanni Pumo picture Michael Giovanni Pumo · Apr 24, 2015

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;
}