我正在使用以下代码在菜单项之间添加分隔符:
#navigation_center li:before {
content: "| ";
color: #fff;
}
Run Code Online (Sandbox Code Playgroud)
现在我希望第一个项目前面没有分隔符,所以我想出了以下代码:
#navigation_center li:before:first-child {
content: none;
}
Run Code Online (Sandbox Code Playgroud)
但那没有做任何事情.是否可以结合:before和:first-child?
hra*_*dac 71
尝试
#navigation_center li:first-child:before {
content: '';
}
Run Code Online (Sandbox Code Playgroud)
编辑:我想通过FelipeAls发表的评论来扩展这个答案.使用的原始问题:first不是有效的CSS选择器.相反,使用:first-child.伪选择器的顺序也很重要.第一个子选择器必须首先出现.
我倾向于将其:before视为选择器的一种修饰符.它实际上并不是仅选择元素之前的空格元素.
虽然hradac的回答应该是我认为最好通过一些可能的排列来帮助新手.
.works:first-child:before
{
color: green;
content: 'working ';
}
.works:not(:first-child):after
{
color: green;
content: ' is working';
}
.broken:before:first-child
{
color: red;
content: 'this will never show up';
}
.broken:after:not(:first-child)
{
color: red;
content: 'and this will not show up either';
}Run Code Online (Sandbox Code Playgroud)
works:
<div>
<div class='works'>
something
</div>
<div class='works'>
something
</div>
<div class='works'>
something
</div>
</div>
<hr/>
broken:
<div>
<div class='broken'>
something
</div>
<div class='broken'>
something
</div>
<div class='broken'>
something
</div>
</div>Run Code Online (Sandbox Code Playgroud)
让我们把它分开:
div.works在div里面div.broken也在div里面first-child然后选择它前面的空白区域来实现.first-child定义的每个块,然后在它们之前选择空的空间.:before:first-child尝试选择一个空的空间,但随后测试它是否是一个first-child,它不是(因为在技术上它尚未在DOM树),类似的问题是:not(:first-child).