简体   繁体   中英

CSS - Hover on element doesn't apply style to another one

I have a problem with applying style to a div when another div is hovered. Here is my scenario:

<div id="nav">
    <div class="logged"></div>
    <div class="nav_child"></div>
</div>
.logged:hover .nav_child {
    display: initial;
}
#nav .nav_child {
    display: none;
}

But it doesn't work. I also tried .logged:hover > .nav_child and .logged:hover + .nav_child and still nothing. It only works with #nav:hover .nav_child but I need to show it when .logged is hovered, not when #nav is hovered.

Any ideas?

Just solved with the Adjacent sibling combinator . I declare and call 'logged' as id and add + between .logged:hover and .nav_child it works.

Reference: Adjacent sibling combinator: http://css-tricks.com/child-and-sibling-selectors

Old code: http://jsfiddle.net/8rdh7m2j/

Working code:

<div id="nav">
<div class="logged" id="logged">Hello</div>
<div class="nav_child">Puff</div>
</div>
#logged:hover + .nav_child {
display: initial;
}

#nav .nav_child {
display: none;
}

Demo: http://jsfiddle.net/hwh3o8u0/1/

Even just remove the #nav from child and +

.logged:hover+.nav_child {
    display:initial;
}
 .nav_child {
    display: none;
}

http://jsfiddle.net/dz22m10y/

You were on the right track with the .logged:hover + .nav_child approach. The reason it didn't work is that #nav .nav_child has higher specificity (because it includes an ID), and therefore takes precedence over the preceding rule.

Yes, you could solve that by moving to an ID for logged , as you did in your self-answer, but instead of doing that, you could raise specificity of the hovering rule by adding in the ID you've already got there too:

#nav .logged:hover + nav_child {

By the way, such problems can nearly always be tracked down using the style inspector in your browser's dev panel. In this case, you would see both rules, and you would see that the second was overriding the first. That would easily lead you to the conclusion that it is a specificity problem. Most style inspectors will give you the ability to "emulate" a hovering state.

For more information on specificity, see https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity . In your case, your original first rule had a specificity of 20 (two classes), and the second one 101 (one ID and one class).

Here is a good resource that covers this topic http://jsfiddle.net/ThinkingStiff/a3y52/
<div id="nav">
    <div id="one" class="logged"></div>
    <div id="two" class="nav_child"></div>
</div>
#one:hover ~ two,
{
    background-color: black;
    color: white;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM