Reputation: 13275
According to a book, the example below should fade-in and -out the menu, but Instead the menu disappears immediately. I believe the problem is that display: none
take effect too early somehow, but I am not sure since it says display: block
in the animation.
What can I do to make the grey div fade out smooth instead of just disappearing? A solution only using CSS for the animation would be preferred.
CSS
a {
color: white;
text-align: center;
}
.bar {
height: 20px;
background: red;
}
.div {
background: silver;
padding: 10px;
}
@-webkit-keyframes fade {
0% {
opacity: 0;
display: block;
}
100% {
opacity: 1;
display: block;
}
}
@keyframes fade {
0% {
opacity: 0;
display: block;
}
100% {
opacity: 1;
display: block;
}
}
.hidden {
display: none;
-webkit-animation: fade 2s reverse;
animation: fade 2s reverse;
}
.shown {
display: block;
-webkit-animation: fade 2s;
animation: fade 2s;
}
HTML
<div class="bar">
<a href="#" class="click">Click Me</a>
<div class="div shown">
<p>Hello</p>
</div>
</div>
jQuery
$(function() {
$div = $(".div");
var menu = function () {
if ( $div.hasClass("shown")) {
$div.removeClass("shown");
$div.addClass("hidden");
} else {
$div.removeClass("hidden");
$div.addClass("shown");
}
}
menu();
$(".click").bind("click", menu);
});
Fiddle: http://jsfiddle.net/hFdbt/1/
Upvotes: 1
Views: 1667
Reputation: 1308
Since you can not transition on the display element (think of it as a boolean or enum, there is nothing but "true" and "false", as in there is no true.5 ), you must use some other method to hide the element.
In this fiddle (http://jsfiddle.net/3n1gm4/Q5TBN/) I've used the max-height
property and overflow: hidden
along with transition
to set the delay.
.hidden {
-webkit-animation: fade 2s reverse;
animation: fade 2s reverse;
-webkit-transition: 0s all 2s; /* delay this the duration of the animation */
transition-delay: 0s all 2s;
max-height: 0;
padding: 0;
overflow: hidden;
}
.shown {
-webkit-animation: fade 2s;
animation: fade 2s;
max-height: 5000px; /* some number way bigger than it will ever be to avoid clipping */
}
credits: Transitions on the display: property
Upvotes: 0
Reputation: 1305
As i said in my comment, you might just aswell use jquery for it.
jQuery
$(".click").on("click", function() {
$(".div").fadeToggle("slow");
});
HTML
<div class="bar">
<a href="#" class="click">Click Me</a>
<div class="div shown">
<p>Hello</p>
</div>
</div>
Css
a {
color: white;
text-align: center;
}
.bar {
height: 20px;
background: red;
}
.div {
background: silver;
padding: 10px;
display: none;
}
New fiddle: http://jsfiddle.net/QvpS3/
Upvotes: 2