Unwanted CSS delay when setting transition duratio

2019-08-12 17:18发布

问题:

I want the menu to close in the same duration it takes for it to open. For some reason, there is a delay before closing, along with showing some extra space I have no idea where it comes from.

Here is the jsfiddle: https://jsfiddle.net/m9pd8bjh/7/

Here's the CSS code in case you see something wrong immediately:

.hide {
  visibility: hidden;
  overflow: hidden;
  max-height: 0;
}

input[type=checkbox]:checked~.toggleable {
  visibility: visible;
  overflow: visible;
  max-height: 1000px;
}

.toggleable {
  transition: visibility 5s ease-in-out, overflow 2.5s ease-in-out, max-height 2.5s ease-in-out;
}

I'm using a checkbox-label combination to trigger the opening and closing of the menu.

回答1:

The first thing you need to understand is that the visibility property in CSS cannot be animated. This is due to it only having two states (either visible or hidden, nothing in between to facilitate the animation).

If you want to make a fade-in effect, you can use opacity:0; to opacity:1; and give that a transition instead.

The next thing to note is that your animation time is very long, and if you are animating a max-width, you need to shorten the animation time to adjust.

See fiddle : https://jsfiddle.net/m9pd8bjh/12/

And CSS:

.toggleable {
  transition: max-height 0.25s ease-in-out;
}

If you specifically want that long animation timeframe, then you will have to use something other than a max-height solution.

This would then become a new avenue to approach as you would have to use JavaScript, jQuery or some other such framework.

For future reference, here is a fiddle doing the same using jQuery: https://jsfiddle.net/m9pd8bjh/15/

And here is the jQuery code:

$('.toggler').click(function(){
    $('.hide').slideToggle();
});


回答2:

I add another transition when you close the menu and I removed the initial margin of the ul element. Is that effect ok for you ?

CSS code changed

.hide {
  visibility: hidden;
  overflow: hidden;
  max-height: 0;
  transition: visibility 0.5s ease-in-out, overflow 0.5s ease-in-out, max-height 0.5s ease-in-out;
}
#menu-main { margin: 0;   padding: 10px 40px }

input[type=checkbox]:checked ~ .toggleable {
  visibility: visible;
  overflow: visible;
  max-height: 1000px;
  transition: visibility 2.5s ease-in-out, overflow 2.5s ease-in-out, max-height 2.5s ease-in-out;
}

See this fiddle