28

我有一些以下 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-colorof tomato?看来我可以使用:not选择器。

4

3 回答 3

60

两种方式:

您可以设置通用规则,然后为: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; }

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

于 2013-05-30T07:59:36.470 回答
13

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

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

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

这是MDN 文档:正如那里所述,IE < 9 不支持它,而其他浏览器则很好地支持它。

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

于 2013-05-30T07:57:07.300 回答
0

这个对我有用

.candidate_verified_items ul li:not(:last-child),
.candidate_verified_items ul li:first-child:not(:last-child) {
   border-right: 1px dashed #7b8db9;
}
于 2020-10-21T04:12:56.080 回答