CSS Auto hide elements after 5 seconds
YES!
But you can't do it in the way you may immediately think, because you cant animate or create a transition around the properties you'd otherwise rely on (e.g. display
, or changing dimensions and setting to overflow:hidden
) in order to correctly hide the element and prevent it from taking up visible space.
Therefore, create an animation for the elements in question, and simply toggle visibility:hidden;
after 5 seconds, whilst also setting height and width to zero to prevent the element from still occupying space in the DOM flow.
FIDDLE
CSS
html, body {
height:100%;
width:100%;
margin:0;
padding:0;
}
#hideMe {
-moz-animation: cssAnimation 0s ease-in 5s forwards;
/* Firefox */
-webkit-animation: cssAnimation 0s ease-in 5s forwards;
/* Safari and Chrome */
-o-animation: cssAnimation 0s ease-in 5s forwards;
/* Opera */
animation: cssAnimation 0s ease-in 5s forwards;
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
}
@keyframes cssAnimation {
to {
width:0;
height:0;
overflow:hidden;
}
}
@-webkit-keyframes cssAnimation {
to {
width:0;
height:0;
visibility:hidden;
}
}
HTML
<div id='hideMe'>Wait for it...</div>
based from the answer of @SW4, you could also add a little animation at the end.
body > div{
border:1px solid grey;
}
html, body, #container {
height:100%;
width:100%;
margin:0;
padding:0;
}
#container {
overflow:hidden;
position:relative;
}
#hideMe {
-webkit-animation: cssAnimation 5s forwards;
animation: cssAnimation 5s forwards;
}
@keyframes cssAnimation {
0% {opacity: 1;}
90% {opacity: 1;}
100% {opacity: 0;}
}
@-webkit-keyframes cssAnimation {
0% {opacity: 1;}
90% {opacity: 1;}
100% {opacity: 0;}
}
<div>
<div id='container'>
<div id='hideMe'>Wait for it...</div>
</div>
</div>
Making the remaining 0.5 seconds to animate the opacity attribute. Just make sure to do the math if you're changing the length, in this case, 90% of 5 seconds leaves us 0.5 seconds to animate the opacity.
Of course you can, just use setTimeout
to change a class or something to trigger the transition.
HTML:
<p id="aap">OHAI!</p>
CSS:
p {
opacity:1;
transition:opacity 500ms;
}
p.waa {
opacity:0;
}
JS to run on load or DOMContentReady:
setTimeout(function(){
document.getElementById('aap').className = 'waa';
}, 5000);
Example fiddle here.