如何使属性适用于所有后代,而不仅仅是直接子代



在 CSS 中,属性需要什么才能传递给所有子级,而不仅仅是直接子级?

.post>img {
  height: 50%;
  width: 100%;
}
<div class="post">
  <img src="http://cdn1.theodysseyonline.com/files/2015/06/21/635704919336245232-967016789_Hair.jpg" />
  <!--This works, appropriately sizing the image. However, if I nest the image, the properties
    seem to disappear:-->
  <a href="http://theodysseyonline.com/ui/4-reasons-why-should-totally-have-crush-bernie-sanders/111812">
    <img src="http://cdn1.theodysseyonline.com/files/2015/06/21/635704919336245232-967016789_Hair.jpg" />
  </a>
</div>
<!--The sizing on the image disappears :( How can I make all img descendants of 
    .post inherit .post>img's properties?-->

嵌套在 a 标记中的第二个图像不继承 .post>img 的属性。

我认为这是因为它不是直系孩子。如何强制img .post的所有后代继承.post>img后代?

小提琴

只需删除使其仅适用于直接子项的>子选择器)。

.post img {
  height: 50%;
  width: 100%;
}
<div class="post">
  <img src="http://cdn1.theodysseyonline.com/files/2015/06/21/635704919336245232-967016789_Hair.jpg" />
  <a href="http://theodysseyonline.com/ui/4-reasons-why-should-totally-have-crush-bernie-sanders/111812">
    <img src="http://cdn1.theodysseyonline.com/files/2015/06/21/635704919336245232-967016789_Hair.jpg" />
  </a>
</div>

在你的代码中,你使用的是子组合器选择器(>)。

.post > img { ... }

此选择器表示父/子关系。在这种情况下,它针对作为 .post 的子元素的任何img元素。

如果要选择所有子体,可以使用后代组合器选择器

.post img { ... }

此选择器(仅空格)针对作为.post后代的所有img元素。

在 W3.org 了解更多信息:

  • 8.1. 后代组合子
  • 8.2. 子组合器
  • 2. 选择器(完整列表)

相关内容

最新更新