Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is n in nth:child selector in css

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;
}
like image 202
Jitender Avatar asked Oct 20 '13 07:10

Jitender


People also ask

What does N mean in CSS?

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.

What is 2n in CSS?

tr:nth-child(even) or tr:nth-child(2n) Represents the even rows of an HTML table: 2, 4, 6, etc.

What is the nth child in CSS?

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() .

How is the nth child () different from Nth of type selectors?

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 .

What is nth 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.


2 Answers

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)
like image 158
Bram Vanroy Avatar answered Sep 25 '22 01:09

Bram Vanroy


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.

like image 42
Shahar Galukman Avatar answered Sep 27 '22 01:09

Shahar Galukman