nav.main ul ul { position: absolute; list-style: none; display: none; opacity:0; visibility: hidden; padding:10px; background-color: rgba(92,91,87,0.9);-webkit-transition: opacity 600ms, visibility 600ms; transition: opacity 600ms, visibility 600ms;} nav.main ul li:hover ul { display: block; visibility: visible; opacity:1;}
Why is there no transition? If I set
nav.main ul li:hover ul { display: block; visibility: visible; opacity:0;/* changed this line */}
Then the "subnav" will never appear (of course ) but why does the transition on the opacity not trigger? How to get the transition working?
回答1:
As you know the display property cannot be animated BUT just by having it in your CSS it overrides the visibility and opacity transitions.
The solution...just removed the display properties.
nav.main ul ul { position: absolute; list-style: none; opacity:0; visibility: hidden; padding:10px; background-color: rgba(92,91,87,0.9);-webkit-transition: opacity 600ms, visibility 600ms; transition: opacity 600ms, visibility 600ms;} nav.main ul li:hover ul { visibility: visible; opacity:1;}
回答2:
Generally when people are trying to animate display: none what they really want is:
Fade content in, and
Have the item not take up space in the document when hidden
Most popular answers use visibility, which can only achieve the first goal, but luckily it's just as easy to achieve both by using position.
Since position: absolute removes the element from typing document flow spacing, you can toggle between position: absolute and position: static (global default), combined with opacity. See the below example.
You can do this with animation-keyframe rather than transition. Change your hover declaration and add the animation keyframe, you might also need to add browser prefixes for -moz- and -webkit-. See https://developer.mozilla.org/en/docs/Web/CSS/@keyframes for more detailed info.
nav.main ul li:hover ul { display: block; visibility: visible; opacity:1; animation: fade 1s;}@keyframes fade {0%{ opacity:0;}100%{ opacity:1;}}