我有一个具有以下结构的页面。我想为每个“组件-4”应用背景色,但只想为第一个元素“组件-4”应用不同的颜色。如何从其他方面指出第一个元素,我也必须支持IE7和IE8。我不能使用Javascript,我想通过使用css来获得它,可以吗?请给我建议。
<html>
<body>
<div id="component-1">
<div class="component-2">
<div class="component-3">
<div class="component-4">
</div>
</div>
</div>
<div class="component-2">
<div class="component-3">
<div class="component-4">
</div>
</div>
</div>
<div class="component-2">
<div class="component-3">
<div class="component-4">
</div>
</div>
</div>
</div>
</body>
</html>请告诉我..。
发布于 2013-12-31 08:57:40
使用伪类first-child
.component-4{
background:red
}
.component-2:first-child .component-4{
background:green
}演示
发布于 2013-12-31 09:31:32
我不得不说我没有IE7或8,但是我用IE仿真器测试了它。
下面是您需要的一个示例:http://jsfiddle.net/fatgamer85/ffVW3/
您有一个id component-1的元素div,在其中有多个带有重复类component-2, component-3 and component-4的div。
可以使用类单独地对这些元素进行样式设置,如本例所示。改变第一个div (或任何div)的背景色的诀窍是找出您需要更改的div的级别,并将CSS伪类(MDN) (W3S) (CSSTricks)应用到它。
相当简单。以下代码:(1)
.component-2 {
background: red;
}应用具有红色背景的类component-2的所有元素。
以及以下代码:(2)
.component-4{
background: pink;
}应用具有粉红色背景的类component-4的所有元素。根据您的代码,编写上述代码的另一种方法是:(3)
.component-2 .component-4{
background: pink;
}将具有component-4类的所有元素应用于具有粉红色背景的component-2中。
我们知道您的代码中有多个component-2、component-3和component-4类。
在层次结构之后,#component-1有多个component-2,其中有具有component-4的component-3,所以如果省略#component-1,那么在相同层次上有3个component-2类的div。
伪选择器有各种情况的选择器(第一个孩子,最后一个孩子,第n个孩子,偶数,奇数等等)。对于代码,您知道需要更改第一个元素的颜色。
因此,为了改变第一个component-4颜色,我们需要向上遍历树以找到重复的节点。在本例中是component-2。选择使用伪类添加css规则的元素的正确方法是(4)
.component-2:first-child{
/* css rules here */
}既然我们知道在容器中写入的任何内容都适用于类名component-2的第一个div,那么就让我们将该类选择器应用到(3)中提到的上述选择器中的一个。
.component-2:first-child .component-4{
/* css rules here */
}此规则指定只有具有类component-2的子类component-4的第一个div应该应用css规则。
因此,这样做,你将达到你的结果。
您可以通过将伪类更改为:last-child或:nth-child(2)来查看伪类所能产生的差异。
我知道这是一个简单的答案很长的帖子,但我希望你能从中学到一些东西。
干杯!
https://stackoverflow.com/questions/20854528
复制相似问题