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:36

try to understanding this example:
html code

<p>Hover over 1 and 3 gets styled.</p>
<div id="one" class="box">1</div>
<div id="two" class="box">2</div>
<div id="three" class="box">3</div>


<!--css-->
#one:hover ~ #three{
background-color: black;
color: white;
}
.box {
cursor: pointer;
display: inline-block;
height: 30px;
line-height: 30px;
margin: 5px;
outline: 1px solid black;
text-align: center;
width: 30px;
}

when you hover on the box 1 than the box 3 will get black color

查看更多
女痞
3楼-- · 2020-02-17 06:39

You shouldn't change a sibling's style when an event occurs on a different element. It's out of the context of CSS.

Use JavaScript to achieve this, for example:

var wrap = document.getElementById("wrap");
var aDiv = wrap.getElementsByClassName("a")[0];
var bDiv = wrap.getElementsByClassName("b")[0];
aDiv.onmouseover = function() {
    bDiv.style.backgroundColor = "red";
};
aDiv.onmouseout = function() {
    bDiv.style.backgroundColor = "white";
};
查看更多
放我归山
4楼-- · 2020-02-17 06:45

You can use + selector

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

to apply the css for sibling element, or

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

for nested class.

查看更多
登录 后发表回答