Introduction
There are a variety of classes and ID selectors available in CSS. In this specific article, we will study about one of the selectors called nth child selector.
The article will include basic concepts of nth-child selectors. We would also have a look at some of the examples of applying nth child selector to CSS.
What is nth child selector?
The :nth-child(n) selector matches every element that is the nth child of its parent amongst other siblings. Some features of n are:
-
n can be any random number
-
a keyword (odd or even)
-
a formula (like an + b)
Nth child selector matches every element irrespective of the type of parent class. Let us see its syntax and some examples for better understanding.
Syntax
:nth-child(number) {
css declarations;
}
Examples of nth child selector in CSS
Example 1: Functional notation
Code
<!DOCTYPE html>
<html>
<head>
<title>:nth-child() example</title>
<style>
li:nth-child(3n + 1) {
color: orangered;
}
</style>
</head>
<body>
<h3>nth-child(3n + 1)</h3>
<ul>
<li>Python</li>
<li>Java</li>
<li>C++</li>
<li>JavaScript</li>
<li>PHP</li>
<li>SQL</li>
</ul>
</body>
</html>
Output
Explanation
In this example, we can clearly see that list items at position 3n+1 gets colored.
Example 2: Odd
Code
<!DOCTYPE html>
<html>
<head>
<title>:nth-child() example</title>
<style>
li:nth-child(odd) {
color: orangered;
}
</style>
</head>
<body>
<h3>nth-child(odd)</h3>
<ul>
<li>Python</li>
<li>Java</li>
<li>C++</li>
<li>JavaScript</li>
<li>PHP</li>
<li>SQL</li>
</ul>
</body>
</html>
Output
Explanation
In this example, we can clearly see that list items at odd position gets colored.
Example 3: Even
Code
<!DOCTYPE html>
<html>
<head>
<title>:nth-child() example</title>
<style>
li:nth-child(even) {
color: orangered;
}
</style>
</head>
<body>
<h3>nth-child(even)</h3>
<ul>
<li>Python</li>
<li>Java</li>
<li>C++</li>
<li>JavaScript</li>
<li>PHP</li>
<li>SQL</li>
</ul>
</body>
</html>
Output
Explanation
In this example, we can clearly see that list items at even position gets colored.