Css Transition on hover for child element

2020-08-10 06:57发布

问题:

Im trying to pause the display of a child element when it's parent is hovered over.

Html:

<span>
    <div>This Is The Child</div>
    Some Text in the span
</span>

Css:

span { 
    position: relative; 
}
span div { 
    display: none;
    width: 0px;
    opacity: 0;

    transition: width 5s;
    -webkit-transition: width 5s;

    transition: opacity 5s;
    -webkit-transition: opacity 5s;
}
span:hover div {
    display: inline-block;
    width: 150px;
    opacity: 1;
}​

As of right now, when the span is hovered, the div has no delay before it is shown. How would I go about fixing it so there is a pause?

Fiddle here: http://jsfiddle.net/SReject/vmvdK/

A few notes:
I originally tried to transition the display, but as Edward pointed out, that isn't possible, and have sense tried the above which, also, isn't working

SOLVED

It would appear that any "display" property in the "transition to" styling will stop any transition animations from happening. To work around this. I set the width of the child to be displayed to 0px and have it be completely transparent. Then in the "transition to" styling, I set the correct width, and make the div solid:

Html:

<span>
    <div>This Is The Child</div>
    Some Text in the span
</span>

Css:

span { 
    position: relative; 
}
span div { 
    position: absolute;

    width: 0px;
    opacity: 0;
    transition: opacity 5s;
    -webkit-transition: opacity 5s;
}
span:hover div {
    width: 150px;
    opacity: 1;
}​

Fiddle here: http://jsfiddle.net/SReject/vmvdK/

回答1:

According to this article on CSS transitions, which is referenced by the MDN page on CSS transitions, the display property is not one that can be transitioned:

There are several properties or values you’ll want to transition, but which are both unspecced and unsupported at the time of writing:

  • background-image, including gradients
  • ...
  • display between none and anything else

So applying the transition: display 5s; property to your div has no effect.

EDIT:

Based on your updated code, you can achieve the effect you want with opacity and width as long as you don't specify the display property. Simply remove the line

display: none;

from the span div section, and the pop-up menu will use the transitions you specified when you hover over it.

Since the transition from display:none; to display:inline-block can't be animated, this property is probably changed only at the end of the transition - so the opacity animates while the div is still invisible.



回答2:

Have you tried using -webkit-transition-delay: ;? If not, this might be something you are looking for?

Did some changes in the code:

span div { 
position: absolute;
left: 5px;
top: 5px;
border: 1px solid #000;
background-color: #888;
width: 0px;
opacity: 0;
cursor: pointer;

}

span:hover div {
display: inline-block;
-webkit-transition-delay: 2s;
width: 150px;            
opacity: 1;

}​

And here's a demo