CSS:在特定元素悬停时更改“x”类的所有元素

时间:2016-05-17 15:02:30

标签: html css css-selectors

我有一个div元素,我希望在div悬停时所有具有某个类的元素都会改变。 我无法让它发挥作用。我的代码只影响了类的第一个元素,我没有使用:first-child selector ...

这是我的代码: https://jsfiddle.net/f6q4080c/

#hoverme {
  width: 100px; height: 100px; 
  background: blue;
}
.other {
  width: 100px; height: 100px; margin-top: 5px;
  background: red; 
}

#hoverme:hover + .other {
  background: green;
}
<div id="container">
    <div id="hoverme" href="#">Hover me to turn the red ones green.</div>
    <div class="other">I want to turn green.</div>
    <div class="other">I want to turn green, too.</div>
</div>

1 个答案:

答案 0 :(得分:2)

您可以使用sibling selector ~定位特定元素的所有兄弟元素,这会转换所有function1元素&#34;绿色&#34;当你的.other元素悬停时:

hoverme

示例

enter image description here

&#13;
&#13;
/* This will turn all other classes green when hoverme is hovered */
#hoverme:hover ~ .other {
    background: green;
}
&#13;
#hoverme {
  width: 100px;
  height: 100px;
  background: blue;
}
.other {
  width: 100px;
  height: 100px;
  margin-top: 5px;
  background: red;
}
#hoverme:hover ~ .other {
  background: green;
}
&#13;
&#13;
&#13;