问题
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