CSS :nth-child() - Select Every nth Element

The CSS :nth-child(N) pseudo-class is used to select Nth child elements of their parent. For example, the following CSS code, applies style to all P elements, that are the third child their parent:

p:nth-child(3) {color: blue;}

CSS :nth-child() Example

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      p:nth-child(2) {color: palevioletred;}
   </style>
</head>
<body>

   <p>This para one.</p>
   <p>This is para two.</p>
   <p>This is para three.</p>
   <div>
      <p>This is para one, inside DIV.</p>
      <p>This is para two, inside DIV.</p>
   </div>
   
</body>
</html>
Output

This para one.

This is para two.

This is para three.

This is para one, inside DIV.

This is para two, inside DIV.

CSS :nth-child() to Select Elements with Even/Odd Index

The even and odd are keywords in CSS. These two keywords in following example are used, to match with even/odd indexes:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      p:nth-child(even) {background-color: tomato; color: white; padding: 8px;}
      p:nth-child(odd) {background-color: teal; color: white; padding: 8px;}
   </style>
</head>
<body>

   <p>This para one.</p>
   <p>This is para two.</p>
   <p>This is para three.</p>
   <p>This is para four.</p>
   <p>This is para five.</p>
   
</body>
</html>
Output

This para one.

This is para two.

This is para three.

This is para four.

This is para five.

CSS :nth-child() to Select Every Specified Element

We can also use some formula like 3n+1 to select every 3n+1th element. Here the value of n start with 0, and increments by 1, each time. Therefore, 3n+1 gives 1, 4, 7, 10, 13, and so on. Similarly 4n+3 gives 3, 7, 11, 15, and so on.

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      p:nth-child(2n+1) {background-color: rgb(31, 83, 83); color: white; padding: 8px;}
   </style>
</head>
<body>

   <p>This para one.</p>
   <p>This is para two.</p>
   <p>This is para three.</p>
   <p>This is para four.</p>
   <p>This is para five.</p>
   
</body>
</html>
Output

This para one.

This is para two.

This is para three.

This is para four.

This is para five.

CSS Online Test


« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook




Subscribe Us on YouTube