提问者:小点点

当一个元素悬停时,如何影响其他元素


null

null

null

div {
  outline: 1px solid red;
}

#container {
  width: 200px;
  height: 30px;
}

#cube {
  width: 30px;
  height: 100%;
  background-color: red;
}

#cube:hover {
  width: 30px;
  height: 100%;
  background-color: blue;
}
<div id="container">
  <div id="cube">
  </div>
</div>

null


共3个答案

匿名用户

如果多维数据集直接位于容器内:

#container:hover > #cube { background-color: yellow; }

如果多维数据集紧挨着容器(容器关闭标记之后):

#container:hover + #cube { background-color: yellow; }

如果多维数据集位于容器内的某个位置:

#container:hover #cube { background-color: yellow; }

null

#container:hover ~ #cube { background-color: yellow; }

匿名用户

在这个特定的示例中,您可以使用:

#container:hover #cube {
    background-color: yellow;   
}

此示例仅适用于CubeContainer的子级。对于更复杂的场景,您需要使用不同的CSS,或者使用JavaScript。

匿名用户

当悬停在给定元素上时,使用同级选择器是对其他元素进行样式化的一般解决方案,但是只有当其他元素跟随DOM中的给定元素时,它才起作用。当其他元素实际上应该在悬停的元素之前时,我们能做什么呢?假设我们要实现如下所示的信号条评级小部件:

通过将flex-direction设置为reverse,可以很容易地使用CSS flexbox模型来实现这一点,从而使元素以与它们在DOM中的顺序相反的顺序显示。上面的屏幕截图来自这样一个小部件,用纯CSS实现。

null

null

.rating {
  display: flex;
  flex-direction: row-reverse;
  width: 9rem;
}
.rating div {
  flex: 1;
  align-self: flex-end;
  background-color: black;
  border: 0.1rem solid white;
}
.rating div:hover {
  background-color: lightblue;
}
.rating div[data-rating="1"] {
  height: 5rem;
}
.rating div[data-rating="2"] {
  height: 4rem;
}
.rating div[data-rating="3"] {
  height: 3rem;
}
.rating div[data-rating="4"] {
  height: 2rem;
}
.rating div[data-rating="5"] {
  height: 1rem;
}
.rating div:hover ~ div {
  background-color: lightblue;
}
<div class="rating">
  <div data-rating="1"></div>
  <div data-rating="2"></div>
  <div data-rating="3"></div>
  <div data-rating="4"></div>
  <div data-rating="5"></div>
</div>