nth-child不能按预期工作 [英] nth-child does not work as expected
问题描述
当我将divs与我使用nth-child的对象一起添加时,它似乎会出现bug。
When I add divs together with the objects that I use nth-child on, it seems to get buggy.
我会感激任何帮助。 / p>
I'll appreciate any help with this.
<html>
<style>
.documents > a:nth-child(2) {
border:1px solid red;
}
</style>
<div class="documents">
<!-- NO DIVS: WORKS FINE -->
<a href="#">Test</a>
<a href="#">Test</a>
<a href="#">Test</a>
<a href="#">Test</a>
</div>
<br />
<div class="documents">
<div></div><!-- ONE DIV: STARTS WITH THE FIRST OBJECT -->
<a href="#">Test</a>
<a href="#">Test</a>
<a href="#">Test</a>
<a href="#">Test</a>
</div>
<br />
<div class="documents">
<div></div><div></div><!-- TWO DIVS: DOES NOT WORK -->
<a href="#">Test</a>
<a href="#">Test</a>
<a href="#">Test</a>
<a href="#">Test</a>
</div>
</html>
推荐答案
这不是错误行为;对于:nth-child()
是如何工作的只是一个常见的误解。
This is not buggy behavior; there's simply been a common misunderstanding of how :nth-child()
works.
$ c> div 元素到开头,你正在寻找的 a
不再成为第二个孩子整体c $ c>:nth-child(2)意味着)。这是因为当你添加一个 div
时,这将成为第一个孩子;依次,第一个 a
成为第二个孩子,第二个 a
成为第三个孩子。当您添加第二个 div
时, div
成为第二个子级, code>元素类似地推进另一个步骤,因此
a:nth-child(2)
不再匹配任何内容。
When you add div
elements to the beginning, the a
that you're looking for no longer becomes the second child overall (which is what :nth-child(2)
means). This is because when you add one div
, that becomes the first child; in turn, the first a
becomes the second child, and the second a
becomes the third child. When you add a second div
, that div
becomes the second child and the a
elements similarly get pushed forward another step, so a:nth-child(2)
no longer matches anything.
如果你正在寻找第二个 a
而不管它的兄弟姐妹中的任何其他元素类型,请使用 a:nth-of-类型(2)
。
If you're looking for the second a
regardless of any other element types among its siblings, use a:nth-of-type(2)
instead.
这篇关于nth-child不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!