2016-03-09 40 views
1

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 propeties?

JsFiddle

回答

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

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

.post > img { ... } 

此选择器代表父/子关系。在这种情况下,它的目标是.post的孩子的任何img元素。

如果你要选择你可以使用一个后代组合子选择所有后代。

.post img { ... } 

这个选择(只是空格)针对所有img元素是.post后裔。

了解更多W3.org:

相关问题