I am curious about nth child selector in css. But is hard to understand its logic for me now. Below given example highlight first and the last span.
<div>
<span>This span is limed!</span>
<span>This span is not. :(</span>
<em>This one is odd. </em>
<span>Sadly, this one is not...</span>
<span>But this one is!</span>
</div>
span:nth-child(2n+1) {
background-color: green;
}
n represents a natural number. Meaning, [0, 1, 2, 3, 4, 5, ...] In your CSS, 2n+1 thus means: 2*0+1 (= 1 ), 2*1+1 (= 3 ), 2*2+1 (= 5 ), 2*3+1 (= 7 ) and so on.
tr:nth-child(even) or tr:nth-child(2n) Represents the even rows of an HTML table: 2, 4, 6, etc.
The :nth-child() is a CSS pseudo-class selector that allows you to select elements based on their index (source order) inside their container. You can pass in a positive number as an argument to :nth-child() , which will select the one element whose index inside its parent matches the argument of :nth-child() .
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 .
The :nth-of-type() pseudo-class represents an element that has an+b siblings with the same expanded element name before it in the document tree, for any zero or positive integer value of n, and has a parent element.
n
represents a natural number. Meaning, [0, 1, 2, 3, 4, 5, ...]
In your CSS, 2n+1
thus means:
2*0+1
(= 1
), 2*1+1
(= 3
), 2*2+1
(= 5
), 2*3+1
(= 7
) and so on.
Your code basically selects all the odd children. Which could be written much shorter, namely:
nth-child(odd)
For first and last you can use the span:first-child
and span:last-child
selectors.
Regarding the nth-child, it is just repetitive selection of elemetns.
span:nth-child(2n+1)
in example will select 1, 3, 5 etc... all the odd spans.
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