CSS Selector for nth element regardless of parent [duplicate]

。_饼干妹妹 提交于 2021-02-07 08:56:02

问题


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>

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/

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.


回答1:


NO

The spec says:

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.

There is no nth-of-DOM selector.

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

As mentioned in the comments by @Marcos Pérez Gude

"The DOM is a tree. So if you think about it, a node depends always on its parent."




回答2:


try:

div:nth-of-type(1) p:nth-of-type(2) {
    background: red;
}      



回答3:


    div:first-of-type p:nth-of-type(2) {
        background: red;
    }



回答4:


        <div class="highlight">
       <p>The first paragraph.</p>
       <p>The second paragraph.</p>
    </div>

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

Add class or id to the div to highlight the second paragraph only and using class or id you have to style otherwise every 2nd element inside a div will get highlighted

 .highlight p:nth-child(0n+2) {
background: red;
}


来源:https://stackoverflow.com/questions/38657979/css-selector-for-nth-element-regardless-of-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!