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

时间:2016-03-09 01:09:57

标签: css css3 css-selectors

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个问题?

JsFiddle

2 个答案:

答案 0 :(得分:2)

只需移除>子选择器),使其仅适用于直接子女。

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

答案 1 :(得分:1)

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

.post > img { ... }

此选择器表示父/子关系。在这种情况下,它会定位img的所有.post元素。

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

.post img { ... }

此选择器(只是空格)定位所有img后代的.post元素。

在W3.org了解详情:

相关问题