How to use the nth-child Selector In CSS

The nth-child selector is a powerful CSS tool that allows us to style elements based on their position within a group.

Example: In this example, we will see the implementation of styling even and odd elements using the nth-child selector.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width,
                   initial-scale=1.0">
    <link rel="stylesheet" 
          href="style.css">
    <title>Even and Odd Styling</title>
</head>
  
<body>
    <h1 style="text-align: center;">    
          w3wiki    
      </h1>
    <div class="container">
        <div class="box">Box 1</div>
        <div class="box">Box 2</div>
        <div class="box">Box 3</div>
        <div class="box">Box 4</div>
    </div>
    <p style="text-align: center;">
      Example of "Using the nth-child Selector"
      </p>
</body>
  
</html>


CSS




/* style.css */
.container {
    margin-top: 40px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-bottom: 40px;
}
  
.box {
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
}
  
/* Styles for even elements */
.box:nth-child(even) {
    background-color: green;
}
  
/* Styles for odd elements */
.box:nth-child(odd) {
    background-color: red;
}


Output:

How to style even and odd elements using CSS ?

In this article, we will learn how to style even and odd elements using CSS. Styling every element uniformly may not always be the best approach. you’ll explore multiple approaches to differentiate between even and odd elements. This is particularly valuable for designing lists, tables, or structured content, where alternating styles enhance readability.

The following techniques can be used to style the elements in an alternative order:

Table of Content

  • Using the nth-child Selector
  • Using Classes
  • Using JavaScript

We will explore the above approaches with the help of suitable examples.

Similar Reads

Using the nth-child Selector

The nth-child selector is a powerful CSS tool that allows us to style elements based on their position within a group....

Using Classes

...

Using JavaScript

...

Contact Us