CSS3伪类不是第一个和最后一个孩子

时间:2013-05-30 07:54:55

标签: css3 pseudo-class

我有以下HTML代码:

<ul>
    <li>number 1</li>
    <li>number 2</li>
    <li>number 3</li>
    <li>number 4</li>
    <li>number 5</li>
    <li>number 6</li>
    <li>number 7</li>
    <li>number 8</li>
    <li>number 9</li>
    <li>number 10</li>
</ul>

我如何使用CSS3伪类来制作不是第一个或最后一个li background-colortomato的{​​{1}}元素?我似乎可以使用:not选择器。

3 个答案:

答案 0 :(得分:42)

两种方式:

您可以设置通用规则,然后为:first-child:last-child项覆盖它。这有助于CSS的优势:

 li { background: red; }
 li:first-child, li:last-child { background: white; }

或者,您可以结合使用:not关键字结合两者:

li { background: white; }
li:not(:first-child):not(:last-child) { background: red; }

在这两个中,我个人更喜欢第一个 - 在我看来,它更容易理解和维护。

答案 1 :(得分:8)

这是一支钢笔 http://codepen.io/vendruscolo/pen/AeHtG

你必须结合两个:not()伪类:

li:not(:first-child):not(:last-child) {
  background: red;
}

这是MDN documentation:如上所述,它不支持IE&lt; 9,虽然它在其他浏览器上得到很好的支持。

如果您需要IE 8支持,则必须依赖Javascript或使用其他类来指示哪个元素是最后一个子元素。实际上,IE 8(及更低版本)不支持:last-child伪类。

答案 2 :(得分:0)

这个对我有用

{
    future: new Date(Date.now() + 60*60*1000),
    future: new Date(Date.now() - 60*60*1000),
}
相关问题