CSS :not(:last-of-type) 不适用于课堂

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23667528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:27:35  来源:igfitidea点击:

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

csscss-selectors

提问by BoltClock

Why doesn't :not(:last-of-type)work in the following situation? How can I fix it?

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

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

JSFiddlehttp: //jsfiddle.net/C23g6/589/

HTML:

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:

CSS:

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

回答by BoltClock

As mentioned, the reason is because :last-of-typematches an element that is the last sibling of its element type, in this case div. Since the last divisn't the last .comment, it doesn't match.

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

Unlike for the first element of a class, there is no way to use pure CSS to match the lastelement of a class, not even with an override. You should either use information about the existing structure to create a selector that will match the element you're looking for, such as:

class 的第一个元素不同,没有办法使用纯 CSS 来匹配class的最后一个元素,甚至没有覆盖。您应该使用有关现有结构的信息来创建一个与您要查找的元素匹配的选择器,例如:

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

Or failing that, add an extra class name to the last .commentand exclude that, or otherwise alter the structure itself to accommodate your needs.

或者失败了,在最后添加一个额外的类名.comment并排除它,或者以其他方式改变结构本身以满足您的需要。

回答by G-Cyrillus

if your structure never change , then :

如果您的结构永远不会改变,那么:

div {
    color:red;
}
:nth-last-of-type(2) {
    color: black;
}

Would be the simple way to do : DEMO, demo 2

将是简单的方法:DEMOdemo 2

:not()has still limitation.

:not()还是有限制的。