我有如下的div结构
<div class="section-outer">
<div class="section-inner">
<div class="type-1"> Hi </div>
<div class="type-2">sub contents 1</div>
<div class="type-2">sub contents 2</div>
</div>
</div>我想在文本“子内容1”之前添加一些内容,我在下面使用CSS。
.section-outer .section-inner > div.type-2:first-child:before {
content: "SOME CONTENT";
}但是上面的css选择器没有选择任何div。有人能帮帮我吗。
发布于 2014-03-16 11:46:02
:first-child伪类选择作为其容器的第一个子元素的元素。.type-2:first-child没有选择任何内容,因为没有一个带有type-2类的div是.section-inner的第一个子级。在CSS选择器4级草案中有:nth-match(1)选择器,但不幸的是,当前浏览器不支持它。
您可以使用这样的解决方案:
.section-outer .section-inner > div.type-2:before {
content: "SOME CONTENT";
}
.section-outer .section-inner > div.type-2 ~ div.type-2:before {
content: none;
}发布于 2014-03-16 11:43:40
这是因为div.type-2是而不是,它是父元素(.section-inner元素)的第一个子元素。
来自MDN
:first-childCSS伪类表示作为父元素的第一个子元素的任何元素。
selector:first-child表示其父元素与selector匹配的第一个子元素,在您的示例中,.section-inner的第一个子元素是div.type-1而不是div.type-2。
换句话说,:first-child伪类通过父类的子树来选择第一个子类,而不是通过element.class列表。
在这个特定的实例中,您可以使用邻接同胞选择器 +来选择第一个div.type-2,如下所示:
这里的例子。
.section-inner > div.type-1 + div.type-2:before {
content: "SOME CONTENT";
}div.type-1 + div.type-2选择器将选择紧跟在div.type-1后面的div.type-2元素。
上述假设假设.type-1和.type-2不经常重复。如果不是这样,您可以使用普通同胞选择器 ~来覆盖content属性,如下所示:
这里的例子。
.section-inner > div.type-2 ~ div.type-2:before {
content: none;
}https://stackoverflow.com/questions/22436274
复制相似问题