CSS Nth-Child



CSS Tutorial  >  Nth-Child

The :nth-child pseudo-class is used to represent one or more of the sibling elements. The syntax for :nth-child is as follows:

[selector-name]:nth-child(<expression>) { [some CSS properties] }

where <expression> can be of the following forms:

  • odd: the 1st, 3rd, 5th, 7th elements, and so on.
  • even: the 2nd, 4th, 6th, 8th elements, and so on.
  • an+b: a and b are integers, and n starts with 0 and keeps increase by 1 until all child elements are accounted for.

Below we some examples. Assume there are 10 child elements.

  • 2n: in this case a=2 and b=0. This refers to the 2nd, 4th, 6th, 8th, and the 10th elements.
  • 2n+1: in this case a=2 and b=1. This refers to the 1st, 3rd, 5th, 7th, and the 9th elements.
  • 0n+1: in this case a=0 and b=1. This refers to only the 1st element, and is equivalent to :first-child.
  • -n+5: in this case a=-1 and b=5. This refers to the 5th, 4th, 3rd, 2nd, and the 1st elements.

Let's take a look at two examples below:

Example 1: Use :nth-child to change the even paragraphs

CSS Declaration

p:nth-child(even) {font-style:italic;}

The following HTML code,

<p>This is paragraph 1.
<p>This is paragraph 2.
<p>This is paragraph 3.
<p>This is paragraph 4.

results in the following:

In Example 1, we used :nth-child to specify that the even number of paragraphs will be in italics.

Example 2: Use :nth-child to change the first two items

CSS Declaration

li:nth-child(-n+2) {font-weight:bold;}

The following HTML code,

<ul>
<li>List item 1
<li>List item 2
<li>List item 3
<li>List item 4
</ul>

results in the following:

In Example 2, when n=0, -n+2=2; when n=1, -n+2=1. Therefore, the texts in the first two rows are bold.

Example 3: Use :nth-child to change non-consecutive items

CSS Declaration

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

The following HTML code,

<ol>
<li>List item 1
<li>List item 2
<li>List item 3
<li>List item 4
<li>List item 5
</ul>

results in the following:

When n=0, 2n+3=3; when n=1, 2n+3=5. Therefore, the third line and the fifth line are shown in red.

Example 4: Use :nth-child to change background color for alternate rows

CSS Declaration

tr:nth-child(2n+1) {background-color:#ccc;}

The following HTML code,

<table>
<tr><td>City</td><td>Country</td></tr>
<tr><td>Los Angeles</td><td>USA</td></tr>
<tr><td>Tokyo</td><td>Japan</td></tr>
<tr><td>Paris</td><td>France</td></tr>
<tr><td>Istanbul</td><td>Turkey</td></tr>
<tr><td>Johannesburg</td><td>South Africa</td></tr>
</table>

results in the following:

In Example 4, we use the :nth-child pseudo class to give odd-number rows a background color of #ccc, while the background color for even-number rows remains white.

Next: CSS List




Copyright © 2024   1keydata.com   All Rights Reserved   Privacy Policy   About   Contact

AdBlock Detected!

Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.