我有如下的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-child
CSS伪类表示作为父元素的第一个子元素的任何元素。
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
复制相似问题