html - CSS:悬停特定元素时更改类 "x"的所有元素

标签 html css css-selectors

我有一个 div 元素,我希望所有具有特定类的元素在 div 悬停时发生变化。 我只是无法让它工作。我的代码只影响类的第一个元素,不,我没有使用 :first-child 选择器...

这是我的代码: 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>

最佳答案

您可以使用 sibling selector ~以特定元素的所有 sibling 为目标,当您的 hoverme 元素悬停时,这会将所有 .other 元素变为“绿色”:

/* This will turn all other classes green when hoverme is hovered */
#hoverme:hover ~ .other {
    background: green;
}

示例

enter image description here

#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>

关于html - CSS:悬停特定元素时更改类 "x"的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37279793/

相关文章:

php - 如何将 HTML 转换为 markdown?

javascript - 如何使用引导列在 PHP 中连续显示图像和文本?

css - 为什么这个 CSS 类样式依赖于顺序?

html - Div 边距设置不正确

html - Bootstrap 页面宽度

javascript - 维基百科 3c 中的 Prims MST 没有意义

javascript - 调整窗口大小时轮播不工作

html - 为什么 <p> 元素是绿色的?

css - 是否可以将 id/class 与属性结合起来?

html - CSS - 如何为奇数和偶数div着色?