当鼠标悬停在父元素上时,将样式应用于子元素

4

我有四个div,我想在悬停时更改父div内三个子元素的背景颜色。

当我悬停在父元素上时,我希望用不同的颜色更改#a,#b和#c的背景颜色。

任何帮助都将不胜感激。

#a {
  background: #174259;
  height: 450px;
  width: 450px;
  display: flex;
  margin: auto;
}

#b {
  background: #C32525;
  height: 350px;
  width: 350px;
  display: flex;
  margin: auto;
}

#c {
  background: #FCC459;
  height: 250px;
  width: 250px;
  display: flex;
  margin: auto;
}

.parent>#a:hover {
  background: green;
}
<div class="parent">
  <div id="a">
    <div id="b">
      <div id="c">
      </div>
    </div>
  </div>
</div>

1个回答

1
你希望当鼠标悬停在父元素上时,所有子元素的背景颜色都发生变化。
但是在你的代码中,你将`:hover`应用于了子元素。
.parent > #a:hover {
  background: green;
}

那将限制样式的范围仅限于悬停在特定子元素上时。相反,将:hover应用于父元素,这样当悬停时,所有子元素都可以同时被选中。
.parent:hover > #a {
  background: green;
}

.parent:hover #b {
  background: blue;
}

.parent:hover #c {
  background: gray;
}

#a {
  background: #174259;
  height: 450px;
  width: 450px;
  display: flex;
  margin: auto;
}

#b {
  background: #C32525;
  height: 350px;
  width: 350px;
  display: flex;
  margin: auto;
}

#c {
  background: #FCC459;
  height: 250px;
  width: 250px;
  display: flex;
  margin: auto;
}

.parent:hover>#a {
  background: green;
}

.parent:hover #b {
  background: blue;
}

.parent:hover #c {
  background: gray;
}
<div class="parent">
  <div id="a">
    <div id="b">
      <div id="c">
      </div>
    </div>
  </div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接