0
0
CssHow-ToBeginner · 3 min read

How to Select Even and Odd Elements in CSS Easily

Use the CSS pseudo-classes :nth-child(even) to select even elements and :nth-child(odd) to select odd elements within a parent. These selectors apply styles to elements based on their position in the HTML structure.
📐

Syntax

The :nth-child() pseudo-class selects elements based on their position among siblings. Use :nth-child(even) to target even-numbered elements and :nth-child(odd) to target odd-numbered elements.

  • :nth-child(even) matches 2nd, 4th, 6th, etc.
  • :nth-child(odd) matches 1st, 3rd, 5th, etc.
css
selector:nth-child(even) {
  /* styles for even elements */
}

selector:nth-child(odd) {
  /* styles for odd elements */
}
💻

Example

This example shows how to color even list items light gray and odd list items white for better readability.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Even and Odd CSS Example</title>
<style>
ul li:nth-child(even) {
  background-color: #f0f0f0;
}
ul li:nth-child(odd) {
  background-color: #ffffff;
}
ul {
  list-style: none;
  padding: 0;
  max-width: 200px;
  font-family: Arial, sans-serif;
}
ul li {
  padding: 10px;
  border: 1px solid #ccc;
}
</style>
</head>
<body>
<ul>
  <li>Item 1 (odd)</li>
  <li>Item 2 (even)</li>
  <li>Item 3 (odd)</li>
  <li>Item 4 (even)</li>
  <li>Item 5 (odd)</li>
</ul>
</body>
</html>
Output
A vertical list of 5 items where odd items have white background and even items have light gray background.
⚠️

Common Pitfalls

One common mistake is confusing :nth-child() with :nth-of-type(). :nth-child() counts all element types, so if your list has mixed elements, the selection may not work as expected.

Also, remember that counting starts at 1, so :nth-child(odd) selects the first element, not zero.

css
/* Wrong: expecting to select only even <li> but mixed elements exist */
ul li:nth-child(even) {
  background-color: yellow;
}

/* Right: use nth-of-type to select even <li> elements only */
ul li:nth-of-type(even) {
  background-color: yellow;
}
📊

Quick Reference

SelectorWhat it selects
:nth-child(even)All even-numbered child elements (2nd, 4th, 6th, ...)
:nth-child(odd)All odd-numbered child elements (1st, 3rd, 5th, ...)
:nth-of-type(even)Even-numbered elements of the same type among siblings
:nth-of-type(odd)Odd-numbered elements of the same type among siblings

Key Takeaways

Use :nth-child(even) and :nth-child(odd) to style even and odd elements respectively.
Counting starts at 1, so :nth-child(odd) selects the first element.
Use :nth-of-type() when you want to select even or odd elements of a specific type.
These selectors help improve readability and design by alternating styles.
Always test your selectors with your HTML structure to avoid unexpected results.