According to http://nthmaster.com/, when styling a range of elements by nth-child, we must do this:
:nth-child(n+4):nth-child(-n+8)
If we use only one :nth-child()
, then we see that it styles all elements by that formula.
How does each of these two :nth-child()
selectors cancel the other's influence on elements which are out of the range?
The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.
The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
Use the querySelector() method to get the nth child of an element, e.g. document. querySelector('#parent :nth-child(3)') . The :nth-child pseudo class returns the element that matches the provided position. Here is the HTML for the examples in this article.
As a general rule, if you want to select an interval of a selector regardless of the type of element it is, use nth-child . However, if you want to select a specific type only and apply an interval selection from there, use nth-of-type .
Combining simple selectors in this way simply means you're looking for elements that match all of the given conditions simultaneously. Combining pseudo-classes is no different from combining other kinds of simple selector, for example div.example
or input[type="checkbox"]:checked
.
So :nth-child(n+4):nth-child(-n+8)
just means any element that is both :nth-child(n+4)
and :nth-child(-n+8)
. This can only be a subset of the matches of either selector when used alone.
And that is how you get a range of elements.
How do you tell which elements will be matched? Simple: look at the B in each An+B expression:
:nth-child(n+4)
matches children starting from the 4th (inclusive):nth-child(-n+8)
matches children up to and including the 8thHow this all works is already illustrated in the website that you link to, but the preceding examples use :nth-child(n+6)
and :nth-child(-n+9)
separately, which may be a little confusing. Here's a more consistent example to illustrate how the two selectors combine (ignore the ::before
/::after
/content
bits in the CSS — just focus on the output):
li::before {
content: 'li';
}
li:nth-child(n+4)::before {
content: 'li:nth-child(n+4)';
}
li:nth-child(-n+8)::after {
content: ':nth-child(-n+8)';
}
<ol>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ol>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With