CSS最后一个子select器:select特定类的最后一个元素,而不是父代的最后一个子元素?

<div class="commentList"> <article class="comment " id="com21"></article> <article class="comment " id="com20"></article> <article class="comment " id="com19"></article> <div class="something"> hello </div> </div> 

我想select#com19

 .comment { width:470px; border-bottom:1px dotted #f0f0f0; margin-bottom:10px; } .comment:last-child { border-bottom:none; margin-bottom:0; } 

只要我有另一个div.something作为最后一个孩子在commentList中实际上不工作。 在这种情况下是否可以使用最后一个子select器来selectarticle.comment的最后一个外观?

的jsfiddle

:last-child只有当有问题的元素是容器的最后一个子元素时,最后一个子元素才起作用,而不是特定元素types的最后一个元素。 为此,您需要:last-of-type

http://jsfiddle.net/C23g6/3/

按照@ BoltClock的评论,这只是检查最后article元素,而不是.comment类的最后一个元素。

HTML

 <div class="commentList"> <article class="comment " id="com21"></article> <article class="comment " id="com20"></article> <article class="comment " id="com19"></article> <div class="something"> hello </div> </div> 

CSS

 body { background: black; } .comment { width:470px; border-bottom:1px dotted #f0f0f0; margin-bottom:10px; } .comment:last-of-type { border-bottom:none; margin-bottom:0; } 

如果您要浮动元素,则可以颠倒顺序

float: right; 而不是float: left;

然后用这个方法select一个类的第一个孩子。

 /* 1: Apply style to ALL instances */ #header .some-class { padding-right: 0; } /* 2: Remove style from ALL instances except FIRST instance */ #header .some-class~.some-class { padding-right: 20px; } 

这实际上是将类应用到LAST实例,因为它现在是相反的顺序。

这是你的一个工作例子:

 <!doctype html> <head><title>CSS Test</title> <style type="text/css"> .some-class { margin: 0; padding: 0 20px; list-style-type: square; } .lfloat { float: left; display: block; } .rfloat { float: right; display: block; } /* apply style to last instance only */ #header .some-class { border: 1px solid red; padding-right: 0; } #header .some-class~.some-class { border: 0; padding-right: 20px; } </style> </head> <body> <div id="header"> <img src="some_image" title="Logo" class="lfloat no-border"/> <ul class="some-class rfloat"> <li>List 1-1</li> <li>List 1-2</li> <li>List 1-3</li> </ul> <ul class="some-class rfloat"> <li>List 2-1</li> <li>List 2-2</li> <li>List 2-3</li> </ul> <ul class="some-class rfloat"> <li>List 3-1</li> <li>List 3-2</li> <li>List 3-3</li> </ul> <img src="some_other_img" title="Icon" class="rfloat no-border"/> </div> </body> </html> 

我猜最正确的答案是:使用:nth-child (或在这个特定的情况下,其对应的:nth-last-child )。 大多数只知道这个select器的第一个参数来获取基于n的计算项目的范围,但它也可以采取“任何CSSselect器”的第二个参数。

您的情况可以通过这个select器来解决: .commentList .comment:nth-last-child(1 of .comment)

但是,在技术上正确并不意味着你可以使用它,因为这个select器现在只在Safari中实现。

进一步阅读:

这个解决scheme呢?

 div.commentList > article.comment:not(:last-child):last-of-type { color:red; /*or whatever...*/ }