2011-03-27 89 views
220

后,我有元素的列表,这些风格像这样的:One | Two | Three | Four | FiveCSS:没有(:最后一子):选择

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 |代替任何人都知道如何选择除最后一个元素外的所有元素?

你可以看到:not()选择here

+0

这种行为似乎是在Chrome 10中的错误它为我在Firefox 3.5。 – duri 2011-03-27 14:56:23

回答

309

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

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

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

li+li:before 
{ 
    content: '| '; 
} 
+7

之后这实际上是让它在IE8上工作的唯一方式(对不起,IE7和更早版本没有cheetos)。 'li:不是(:第一个孩子):之前的'对于老版本的Internet Explorer来说有点太可怕了。 – 2012-10-22 16:39:52

22

你的榜样的定义文字作品完美地在Chrome 11我。也许你的浏览器不支持:not()选择器?

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

+7

我通过做'li:not(:first-child):before'来解决这个问题,并在之前添加了竖线。我正在使用稳定版本的Chrome,但似乎不支持最后一个孩子。金丝雀身材呢。谢谢你的回答。 – 2011-03-30 22:40:03

+0

似乎即使在2013年,Chrome也不支持它? – MikkoP 2013-03-24 12:53:19

10

您的样品不能在IE工作对我来说,你有你的文档中指定DOCTYPE头呈现您的网页在IE标准的方式来使用内容的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:   " |"; 
} 

但你仍然需要指定文档类型

而第三种方式是使用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> 

优势的第三种方式是,你没有指定文档类型和jQuery将采取兼容性的照顾。

+6

<!DOCTYPE html>是新的HTML5标准。 – 2011-03-30 22:37:57

+1

这是处理这个问题的绝佳方式。我一直在努力:最后一个孩子,然后我找到了你的答案。这个是完美的!:not(:last-of-type):在 – Firze 2016-10-20 10:44:58

130

每件事似乎都是正确的。你可能想要使用下面的CSS选择器而不是你使用的。

ul > li:not(:last-child):after 
+2

谢谢,这与我在最后使用的类似:'li:not(:first-child):before'。请参阅回答帖子中的评论。 – 2013-06-17 10:08:36

+1

这很美。不知道为什么它不是公认的答案! – 2018-02-13 21:12:22

5

使用CSS

一个例子
ul li:not(:last-child){ 
     border-right: 1px solid rgba(153, 151, 151, 0.75); 
    } 
相关问题