Can you apply a CSS hover effect to an element that’s not a child of the hovered element?
I was not sure if this is possible or not. I am working in CSS3 animations right now and I need to hover on a link that will effect other div element(non-child) on the page. I was not sure if there is a work around or not.
<style type="text/css">
#header {
background-color:red;
}
#header:hover .element {
background-color:blue;
}
.element {
background-color:green;
}
</style>
-
<header id="header">
开发者_如何学运维 <li><a href="#">Hover</a></li>
</header>
<div class="element" >
<p>hello world </p>
</div>
Since these are adjacent siblings, you can use the adjacent sibling selector: +
.
#header:hover + .element {
background-color:blue;
}
This is well supported in most modern browsers*. IE7 can be buggy. IE6 and below does not support it.
* One of the other answers mentions the general sibling selector, which does not work in Webkit when used with a dynamic pseudo-class like :hover
due to this bug. Take note that this same bug will cause problems in Webkit if you attempt to stack adjacent sibling selectors with a dynamic pseudo-class. For example, #this:hover + sibling + sibling
will not work in Webkit.
There is the general sibling selector (~
) that selects sibling elements.
So with the HTML you’ve posted, #header:hover ~ .element
would select <div class="element">
when it’s a subsequent sibling of the hovered header.
Even IE 7 supports it, so you're on relatively solid ground.
Re the sibling selector webkit bug, this article has a css only workaround:
http://css-tricks.com/webkit-sibling-bug/
Quoting:
body { -webkit-animation: bugfix infinite 1s; }
@-webkit-keyframes bugfix { from { padding: 0; } to { padding: 0; } }
Above creates an animation on the page and this magically seems to fix the problem. The above can be added directly to main css or a create a webkit only stylesheet to go with your ie hacks one.
Would recommend the webkit only stylesheet something like:
<link rel="stylesheet" media="only screen and (-webkit-min-device-pixel-ratio:0)" href="webkit.css"/>
as it hides it from other browsers and can be more easily removed in the future once the bug is fixed.
Unfortunately this will not work unless your .element class is within the .bgchange element. That's the nature of the cascade: you cannot (through CSS alone) affect DOM elements that are structurally / heirarchically removed from each other.
I dont think so. This construction: #header .bgchange:hover .element indicates that .element is inside the .bgchange. I guess this one needs JS
精彩评论