在孩子悬停时,更改父容器的背景颜色(仅限 CSS)

新手上路,请多包涵

这是一个常见的问题。它几乎总是作为这个问题的副本立即关闭: Is there a CSS parent selector?

副本很好地指出父元素不能用 CSS 定位。但它对原始问题几乎没有提供任何指导,这可能会陷入 XY 问题

在这种特殊情况下……

悬停子项时如何更改父项的背景颜色?

…至少有一种 CSS 解决方案可以解决问题。

 <div>
  <a href="#">Anchor Text</a>
</div>

原文由 Michael Benjamin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 585
2 个回答

仅使用 pointer-events:hover

指针事件的兼容性: caniuse.com 。经测试可在 IE 11 和 Edge、Chrome 和 Firefox 上运行。

  • 在 div 上设置 pointer-events: none 。 div 现在将忽略 :hover
   div {
      pointer-events: none;
  }

  • 将父背景设置为在悬停时更改
  div:hover {
      background: #F00;
  }

  • 在孩子上设置 pointer-events: auto 以便仅在孩子悬停时触发悬停事件
  div > a {
      pointer-events: auto;
  }

这是有效的,因为 div 在它的孩子悬停时悬停,并且指针事件仅在那个孩子上用 auto 激活。否则父类会忽略它的 hover 伪类。

例子

注意: IE 11 和 Edge 要求子元素为 display: inline-blockdisplay: block 才能使指针事件起作用。

 div {
  height: 200px;
  width: 200px;
  text-align: center;
  pointer-events: none;
}
div:hover {
  background: #F00;
}
div > a {
  pointer-events: auto;
  display: inline-block;
}
 <div>
  <h1>Heading</h1>
  <a href="#">Anchor Text</a>
</div>

原文由 misterManSam 发布,翻译遵循 CC BY-SA 3.0 许可协议

虽然您不能使用 CSS 选择父元素,但您可以使用另一种方法来完成此任务。

当悬停子项时,您希望父项的背景颜色发生变化。

考虑使用 spread-radius CSS box-shadow 属性 的值。

通过创建一个巨大的扩展半径,您可以更改周围区域的颜色(这在视觉上与父元素没有区别)。

 div {
    overflow: hidden;              /* 1 */
}

a:hover {
    box-shadow: 0 0 0 1000px red;  /* 2 */
}

/* non-essential decorative styles */
div {
  height: 150px;
  width: 150px;
  border: 1px dashed black;
  display: flex;
  justify-content: center;
  align-items: center;
}
 <div>
  <a href="http://www.stackoverflow.com/">Anchor Text</a>
</div>

笔记:

  1. overflow: hidden 限制子框阴影
  2. box-shadow 值如下:

<box-shadow> : <offset-x> <offset-y> <blur-radius> <spread-radius> <color>

  • offset-x ~ 元素的水平距离
  • offset-y ~ 元素的垂直距离
  • blur-radius ~ 使阴影越来越大和透明
  • spread-radius ~ 使阴影扩大(不褪色)

在这种情况下,前三个值无关紧要。

您需要的是 spread-radius 增长很多,然后用 overflow: hidden 将其剪裁到容器中。


如果容器中有另一个元素怎么办?

 <div>
  <h2>Hello</h2>
  <a href="http://www.google.com">Anchor Text</a>
</div>

 div {
    overflow: hidden;
}
a:hover {
    box-shadow: 0 0 0 1000px red;
}
div {
  height: 150px;
  width: 150px;
  border: 1px dashed black;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
 <div>
  <h2>Hello</h2>
  <a href="http://www.stackoverflow.com/">Anchor Text</a>
</div>

您可以将 z-index 应用于兄弟姐妹。

 h2 { z-index: 1; }

而且,因为在这个例子中元素恰好在一个 flex 容器中, 所以它们不需要定位 z-index 工作。

 h2 { z-index: 1; }

div {
    overflow: hidden;
}
a:hover {
    box-shadow: 0 0 0 1000px red;
}
div {
  height: 150px;
  width: 150px;
  border: 1px dashed black;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
 <div>
  <h2>Hello</h2>
  <a href="http://www.stackoverflow.com/">Anchor Text</a>
</div>

原文由 Michael Benjamin 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题