第n个元素的CSS选择器,与父元素无关 [英] CSS Selector for nth element regardless of parent

查看:57
本文介绍了第n个元素的CSS选择器,与父元素无关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

匹配元素的第n个是否有CSS选择器,而与任何父级无关.

Is there a CSS selector for the nth of a matching element, regardless of any parents.

例如在下面如何选择仅第二段".还没有第四个吗?

e.g. in the following how to select just "The second paragraph." without also the fourth one?

<div>
   <p>The first paragraph.</p>
   <p>The second paragraph.</p>
</div>

<div>
   <p>The third paragraph.</p>
   <p>The fourth paragraph.</p>
</div>

我认为p:nth-​​oftype(2)可以做到,但是同时选择了第二个和第四个(这是每个父div的第二个).

I thought p:nth-oftype(2) would do it but that selects both the second and fourth (which is the 2nd of each parent div).

JSFiddle- https://jsfiddle.net/km4nbfz9/

JSFiddle - https://jsfiddle.net/km4nbfz9/

编辑-这只是HTML的一个示例位,问题是如何使与CSS选择器匹配的第n个元素(不管其父级和结构)如何起作用.

EDIT - This is just ONE example bit of HTML, question is how to make this work for the n'th element that matches CSS selector regardless of parents and structure.

推荐答案

> 规范 说:

:nth-​​child(an + b)伪类表示法表示元素在文档树中具有+ b-1 兄弟 的元素,例如n的任何正整数或零值,并且具有 parent 元素.

The :nth-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element.

没有 nth-of-DOM 选择器.

这里的有效词是兄弟姐妹 ..它需要父母,而不是叔叔或祖父母等.

The operative word here is siblings..which requires a parent, not uncles or grandparents etc.

@MarcosPérezGude

"DOM是一棵树.因此,考虑一下,节点始终取决于其父节点."

这篇关于第n个元素的CSS选择器,与父元素无关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆