409

我有一个元素列表,其样式如下:

ul {
    list-style-type: none;
    text-align: center;
}

li {
    display: inline;
}

li:not(:last-child):after {
    content:' |';
}
<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
</ul>

输出One | Two | Three | Four | Five |而不是One | Two | Three | Four | Five

任何人都知道如何 CSS 选择除最后一个元素之外的所有元素吗?

您可以在此处:not()查看选择器的定义

4

9 回答 9

466

如果不是选择器有问题,您可以设置所有这些并覆盖最后一个

li:after
{
  content: ' |';
}
li:last-child:after
{
  content: '';
}

或者如果你可以使用之前,不需要最后一个孩子

li+li:before
{
  content: '| ';
}
于 2012-03-16T12:03:48.993 回答
262

每件事似乎都是正确的。您可能希望使用以下 css 选择器而不是您使用的选择器。

ul > li:not(:last-child):after
于 2013-06-17T10:06:39.250 回答
31

对我来说它工作正常

&:not(:last-child){
            text-transform: uppercase;
        }
于 2018-12-14T12:44:59.893 回答
26

您所写的示例对我来说在 Chrome 11 中完美运行。也许您的浏览器不支持:not()选择器?

您可能需要使用 JavaScript 或类似工具来完成此跨浏览器。jQuery在其选择器 API 中实现了:not() 。

于 2011-03-27T14:47:12.407 回答
21

使用 CSS 的示例

  ul li:not(:last-child){
        border-right: 1px solid rgba(153, 151, 151, 0.75);
    }
于 2017-07-26T20:57:11.923 回答
10

您的示例在 IE 中对我不起作用,您必须在文档中指定Doctype 标题才能在 IE 中以标准方式呈现您的页面,以使用 content CSS 属性:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<html>

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
</ul>

</html>

第二种方法是使用 CSS 3 选择器

li:not(:last-of-type):after
{
    content:           " |";
}

但是你仍然需要指定 Doctype

第三种方法是使用带有一些脚本的 JQuery,如下所示:

<script type="text/javascript" src="jquery-1.4.1.js"></script>
<link href="style2.css" rel="stylesheet" type="text/css">
</head>
<html>

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
</ul>

<script type="text/javascript">
  $(document).ready(function () {
      $("li:not(:last)").append(" | ");
    });
</script>

第三种方式的优点是您不必指定 doctype 并且 jQuery 将负责兼容性。

于 2011-03-27T15:28:02.730 回答
1

删除 : before last-child 和 :after and used

 ul li:not(last-child){
 content:' |';
}

希望它应该工作

于 2019-09-21T23:49:12.840 回答
0

删除 : before last-child 和 :after and used

ul > li:not(:last-child):after {
   border-bottom: none !important;
}
于 2021-08-23T08:26:17.333 回答
-3

你可以试试这个,我知道不是你要找的答案,但概念是一样的。

您在哪里为所有孩子设置样式,然后从最后一个孩子中删除它。

代码片段

li
  margin-right: 10px

  &:last-child
    margin-right: 0

图片

在此处输入图像描述

于 2018-07-06T06:53:32.617 回答