本文介绍了nth-child不响应类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以让nth-child伪选择器与特定类一起工作?

Is it possible to get the nth-child pseudo-selector to work with a specific class?

请参见示例:

我想要第二个DIV.red

I want to have the second DIV.red turn red, but it doesn't apply the color as expected.

不仅如此,但当您指定此项时,它会将第5个DIV更改为红色:

Not only that, but when you specify this, it changes the 5th DIV to red:

div.red:nth-child(6)

当您指定此选项时,它会将第8个DIV更改为红色:

When you specify this, it changes the 8th DIV to red:

div.red:nth-child(9)

它似乎是一个DIV。在示例中只有8个DIV标签,所以我不知道为什么nth-child(9)甚至可以工作。使用Firefox 3.6进行测试,但在我的实际生产代码中,Chrome中也出现了相同的问题。

It seems to be one DIV behind. There are only 8 DIV tags in the example so I don't know why nth-child(9) even works. Testing using Firefox 3.6, but in my actual production code the same problem occurs in Chrome. I'm not understanding something about how this is supposed to work, would appreciate clarification.

此外,这会将第6个DIV更改为红色,但我实际想要的是以将第二个DIV.red更改为红色:

Also, this will change the 6th DIV to red, but what I actually want is for it to change the second DIV.red to red:

div.red:nth-of-type(6)

我不明白为什么nth-child()和nth-因为文档中只有八个相同类型的标签。

And I don't understand why nth-child() and nth-of-type() respond differently, since there are only eight tags of the same type in the document.

推荐答案

没有办法在CSS中按类过滤,因为no :nth-​​of-class()选择器。其中一种方法是将两种不同的 div 放入自己的组中,然后根据这些组进行选择。例如:

There's no way to filter by class in CSS because there's no :nth-of-class() selector. One way around this is to put your two different kinds of divs into their own groups, then select based on those groups. For example:

<div class="orange">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

<div class="red">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

使用此选择器:

div.red div:nth-child(2) {
    background: red;
}






你的问题:


Regarding the last bit of your question:

不应该 >有任何区别。我测试它,和两个伪类工作按预期。但是,一般来说:

For the code you give there shouldn't be any difference. I tested it, and the two pseudo-classes work as expected. But, in general:

:nth-​​child()在整个兄弟姐妹级别操作,其他简单选择器。

:nth-child() operates on an entire level of siblings without regard for any other simple selectors. Then if the nth child is not among what's matched by the simple selectors, nothing is matched.

:nth-​​of-type()

:nth-of-type() operates on a level of siblings of the given type without regard for other simple selectors. Then if the nth element occurring of that type is not among what's matched by the simple selectors, nothing is matched.

这篇关于nth-child不响应类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:46