css - :not(:last-of-type) not working for class

标签 css css-selectors

为什么 :not(:last-of-type) 在以下情况下不起作用?我该如何解决?

JSFiddle:http://jsfiddle.net/C23g6/589/

HTML:

<div class="comment">This is Red</div>
<div class="hello">------------------</div>
<div class="comment">This is Red</div>
<div class="hello">------------------</div>
<div class="comment">Shouldn't be Red</div>
<div class="hello">------------------</div>

CSS:

.comment:not(:last-of-type) {
    color: red;
}

最佳答案

如前所述,原因是因为 :last-of-type 匹配的元素是其元素类型的最后一个兄弟元素,在本例中为 div。由于最后一个 div 不是最后一个 .comment,因此它不匹配。

不同于 the first element of a class , 没有办法使用纯 CSS 来匹配类的 last 元素,即使使用覆盖也是如此。您应该使用有关现有结构的信息来创建一个与您要查找的元素相匹配的选择器,例如:

.comment:not(:nth-last-child(2))

或者做不到这一点,在最后的 .comment 中添加一个额外的类名并将其排除,或者以其他方式更改结构本身以满足您的需要。

关于css - :not(:last-of-type) not working for class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23667528/

相关文章:

jquery - 如何将 jQuery UI 内容背景更改为白色?

css - 我如何在元素及其子元素上使用 css ".not()"

Jquery 在图像之间切换

javascript - 当 iframe 内容的高度改变时自动调整 iframe 高度(同域)

javascript - jquery 图像和背景淡入淡出 onclick

html - 如何只在第一个类型元素中添加内容?

CSS 表 : fixed column with alternate row colors?

css - 如何使用不同的单元格创建自定义表格?

html - CSS - 模糊所有的 child ,除了悬停的 child ,当鼠标悬停在 child 身上时

css - 其他元素数量的div可见性