CSS: before 和: first-child 组合

我使用以下代码在菜单项之间添加分隔符:

#navigation_center li:before {


content: "| ";
color: #fff;


}

现在我希望第一个项目前面没有分隔符,所以我想出了以下代码:

#navigation_center li:before:first-child {


content: none;


}

但是这没有任何作用。有没有可能把: before 和: first-child 结合起来?

104466 次浏览

试试看

#navigation_center li:first-child:before {
content: '';
}

Edit: I wanted to expand on this answer with comments made by FelipeAls. The original question used :first which is not a valid CSS selector. Instead, use :first-child. Also the order of the pseudo-selectors is important. The first child selector must come first.

我倾向于认为 :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';
}
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>

我们来分析一下:

  • 三个 div.works在一个 div 中
  • Three div.broken are also inside a div
  • CSS 的第一个规则是在。它通过选择 first-child,然后选择它之前的空白空间来实现。
  • 第二个规则在第一个块之后添加“正在工作”,类似地,它首先选择不属于 first-child定义的每个块,然后选择它们之前的空白。
  • 以下两条规则将不会找到要附加到的块。:before:first-child尝试选择一个空白空间,然后测试它是否是 first-child(因为技术上它还没有出现在 DOM 树中) ,类似的问题出现在 :not(:first-child)上。