CSS :hover on other element?

2020-02-17 06:05发布

Short question: Why does the background-color of .b does not change when I hover? .a?

CSS

.a {
    color: red;
}

.b {
    color: orange;
}

.a:hover .b {
    background-color: blue;
}

HTML

<div id="wrap">
    <div class="a">AAAA</div>
    <div class ="b">BBBB</div>
</div>

http://jsfiddle.net/2NEgt/

标签: css hover
9条回答
做自己的国王
2楼-- · 2020-02-17 06:24

Can you not do something like a:hover + b? see http://meyerweb.com/eric/articles/webrev/200007a.html

查看更多
▲ chillily
3楼-- · 2020-02-17 06:25

You need to have .a:hover + .b instead of .a:hover .b

.a:hover .b would work for a structure like

<div class="a">AAAA
  <div class ="b">BBBB</div>
</div>

If at some point you'll need to have some elements between .a and .b, then you'll need to use .a:hover ~ .b, which works for all siblings of .a coming after it, not just the next one.

Demo http://jsfiddle.net/thebabydino/EajKf/

查看更多
何必那么认真
4楼-- · 2020-02-17 06:32

There are two things you can do.

Either change your HTML to make .b a child of .a

<div id="wrap">
    <div class="a">AAAA
       <div class ="b">BBBB</div>        
    </div>
</div>

OR

Change your css to use the adjacent selector

.a:hover + .b {
    background-color: blue;
}
查看更多
男人必须洒脱
5楼-- · 2020-02-17 06:34

because .b isn't a child of .a, so that selector isn't finding anything. Use javascript to do what you want to do there.

查看更多
萌系小妹纸
6楼-- · 2020-02-17 06:35

Jquery is a good and easy solution:

html:

<div class="a">AAA</div>
<div class="b">BBB</div>

script: Put this script into your html if you want. That's all.

<script>
      $(".a").mouseover(function(){
        $(".b").css("color", "blue"); 
      });
      $(".a").mouseleave(function(){
        $(".b").css("color", "red");
      });
</script>
查看更多
Explosion°爆炸
7楼-- · 2020-02-17 06:36
登录 后发表回答