Transitions on the display: property
I'm currently designing a kind of CSS 'mega dropdown' menu - basically a normal CSS-only dropdown menu, but one that contains different types of content.
At the moment, it appears that CSS3 Transitions don't apply to the 'display' property , ie you can't do any sort of transition from display: none
to display: block
(or any combination).
Can anyone think of a way for the second-tier menu from the above example to 'fade in' when someone hovers over one of the top level menu items?
I'm aware that you can use transitions on the visibility:
property, but I can't think of a way to utilise that effectively.
I've also tried using height but that just failed miserably.
I'm also aware that it's trivial to achieve this using JavaScript, but I wanted to challenge myself to use just CSS and I think I'm coming up a little short.
All and any suggestions most welcome.
您可以连接两个或更多的转换,而visibility
是这次派上用场的。
div {
border: 1px solid #eee;
}
div > ul {
visibility: hidden;
opacity: 0;
transition: visibility 0s, opacity 0.5s linear;
}
div:hover > ul {
visibility: visible;
opacity: 1;
}
<div>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
You need to hide the element by other means in order to get this to work.
I accomplished the effect by positioning both <div>
s absolutely and setting the hidden one to opacity: 0
.
If you even toggle the display
property from none
to block
, Your transition on other elements will not occur.
To work around this, always allow the element to be display: block
, but hide the element by adjusting any of these means:
height
to 0
. opacity
to 0
. overflow: hidden
. There are likely more solutions, but you cannot perform a transition if you toggle the element to display: none
. For example, you may attempt to try something like this:
div {
display: none;
transition: opacity 1s ease-out;
opacity: 0;
}
div.active {
opacity: 1;
display: block;
}
But that will not work. From my experience, I have found this to do nothing.
Because of this, you will always need to keep the element display: block
- but you could get around it by doing something like this:
div {
transition: opacity 1s ease-out;
opacity: 0;
height: 0;
overflow: hidden;
}
div.active {
opacity: 1;
height: auto;
}
At the time of this post all major browsers disable CSS transitions if you try to change the display
property, but CSS animations still work fine so we can use them as a work-around.
Example Code:- (You can apply it to your menu accordingly) Demo
Add the following CSS to your stylesheet:-
@-webkit-keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
Then apply the fadeIn
animation to the child on parent hover:- (and of course set display: block
)
.parent:hover .child {
display: block;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s;
}
链接地址: http://www.djcxy.com/p/4704.html
上一篇: 点击一个DIV到底层元素
下一篇: 显示屏上的过渡:属性