如何使用纯CSS选择除第一个和最后一个以外的所有列表项?

6

我有一个HTML列表,需要选择除第一个和最后一个元素以外的所有元素。

目前我的尝试是这样的:

.inputList li:not(:first-child):not(:last-child) {
    // stuff
    }

不太有效...有没有更好的方法,而且还能在IE上运行?

感谢提供意见!

4个回答

10

您可以为所有子元素指定一个声明,然后为第一个和最后一个子元素进行覆盖

.example > LI {background: green; }

.example > LI:first-child,
.example > LI:last-child {background: none; }

是的。我想这是正确的方法。谢谢! - frequent

5

写成这样:

.inputList li:first-child, .inputList li:last-child{
  color:red;
}

注意::first-child 可在 IE7 及以上版本中使用。 :last-child 可在 IE9 及以上版本中使用。


我需要除第一个和最后一个元素之外的所有元素。 - frequent

4

第一个元素可以被忽略,因为

li + li{border-left: 1px solid #000;}

3

我刚刚发现了另一种方法来做这件事,所以只是为了文档而发布:

.inputList li + li:not(:last-child) {
    background-color: green;
}

在我的情况下,我想要在列表项后面添加逗号。
.education li:not(:last-child):after {
        content: ",";
      }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接