Aswin

July 24, 2024

CSS Selector : nth-child selector

:nth-child selector

The nth-child pseudo-class in CSS is used to select elements based on their position within a parent element. It allows you to target elements that match a specific pattern, such as every third element, every even element, or every odd element.

 

odd/ even selector

We can select every odd or even element number by using these attributes.

li:nth-child(odd){
    color: red;
}

The result is that only the odd items are selected.

 

li:nth-child(even){
    color: red;
}

In this example, the selector takes all even HTML elements and applies the styling

 

nth-child basic selector

We can define which number of an element we want to select. So let’s say we want to select the fourth list element.

li:nth-child(4) {
	color: red;
}

Every x selector

Something cool we can do with the nth-child selector is select every x element. So let’s say, for example we want every fourth element:

li:nth-child(4n) {
  	color: red;
}

Or if we want to include the first item:

li:nth-child(4n+1) {
	color: red;
}

The formula is constructed using the syntax an+b. Where,
: a is an integer value
: b is an integer and is required if an operator is included in the formula
: n is all nonnegative integers, starting from 0.

 

We can also start from the second element, for instance:

li:nth-child(4n+2) {
	color: red;
}

Select every item but the first x items

We can even use a selector that selects every tag but the first three elements.

li:nth-child(n+4) {
	color: red;
}

Select first x number of elements

we can do is select only the first x amount. Let’s get the first three items:

li:nth-child(-n+3) {
	color: red;
}

Select first and last elements

li:first-child {
	color: red;
}

 

li:last-child {
	color: red;
}

 

li:nth-last-child(2) {
	color: red;
}

And some examples of calculations,

:nth-child(5n) : [5×0]= 0, [5×1]= 5, [5×2]= 10, [5×3]= 15, etc

:nth-child(n+7) : [0+7]= 7, [1+7]= 8, [2+7]= 9, etc.

:nth-child(3n+4) : [(3×0)+4]= 4, [(3×1)+4]= 7, [(3×2)+4]= 10, [(3×3)+4]= 13, etc.

:nth-child(-n+3) : [ -0+3, -1+3, -2+3 ] = [ 3,2,1,..etc ]

 

Browser support for nth-child selector

 

Top comments
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments