fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← CSS

CSS / 7 MIN READ

Nth Child

Master the nth-child selector for precise element targeting in CSS.

From the original Fervor library. Examples may use older package versions.

Nth childern: psuedo-selector

In CSS, the :nth-child() selector allows you to select elements based on their position within a parent element. It is a powerful tool for targeting specific elements in a set of siblings.

The :nth-child() selector accepts an argument in the form of a formula (an+b) that determines which elements to select. Here’s the basic syntax:

:nth-child(an+b) {
  /* CSS rules */
}

Let’s break down the formula:

  • n represents the index of the element. It starts from 0 and increments by 1 for each subsequent sibling element.
  • a is an optional multiplier. If specified, it determines the frequency of the elements to be selected.
  • b is an optional offset. It determines the starting position of the selection.

Here are a few examples to illustrate how to use the :nth-child() selector:

  1. Select the first child element:
:nth-child(1) {
  /* CSS rules */
}
  1. Select even-numbered elements:
:nth-child(2n) {
  /* CSS rules */
}
  1. Select odd-numbered elements:
:nth-child(2n+1) {
  /* CSS rules */
}
  1. Select every third element, starting from the fourth element:
:nth-child(3n+4) {
  /* CSS rules */
}
  1. Select the last two elements:
:nth-child(-n+2):last-child {
  /* CSS rules */
}

These are just a few examples, and you can create more complex selectors by adjusting the formula to fit your specific needs. Remember to replace the /* CSS rules */ with the styles you want to apply to the selected elements.

Bonus more ways to use nth child

Certainly! The :nth-child() selector has some interesting tricks and use cases. Here are a few cool tricks you can do with :nth-child():

  1. Alternate Row Styles: You can apply different styles to alternate rows in a table by using the :nth-child(odd) and :nth-child(even) selectors. For example:
tr:nth-child(odd) {
  background-color: lightgray;
}

tr:nth-child(even) {
  background-color: white;
}
  1. Target Specific Elements in a List: If you have a list and want to style specific items differently, you can use :nth-child() to target those elements. For instance, to make the third list item red:
li:nth-child(3) {
  color: red;
}
  1. Create a Grid Layout: You can use :nth-child() to create grid-like layouts by specifying the number of items per row. For example, if you want a 3-column layout:
.item:nth-child(3n+1) {
  clear: left;
}

This clears the float and starts a new row every third element, creating a grid effect.

  1. Highlight the First Letter of Each Paragraph: To highlight the first letter of each paragraph, you can use the :first-letter pseudo-element in combination with :nth-child(1). For example:
p:nth-child(1)::first-letter {
  font-size: 24px;
  color: blue;
}
  1. Style Elements in a Range: You can style elements within a specific range by combining multiple :nth-child() selectors. For example, to select and style the third, fourth, and fifth elements:
:nth-child(n+3):nth-child(-n+5) {
  /* CSS rules */
}

Here are a few more examples of cool tricks you can achieve using the :nth-child() selector:

  1. Diagonal Background Pattern: You can create a diagonal background pattern by using a combination of :nth-child() and transform property. For example, to create a checkerboard pattern:
div:nth-child(2n) {
  transform: translateY(50%);
}
  1. Highlight Every Nth Element: To highlight every 4th element, you can use :nth-child(4n). For instance, to apply a different background color:
div:nth-child(4n) {
  background-color: yellow;
}
  1. Creating Progress Bars: You can create progress bars using :nth-child() and adjusting the width of the elements. For example, to create a 5-step progress bar:
.step:nth-child(-n+3) {
  background-color: green;
}

.step:nth-child(4) {
  background-color: orange;
}

.step:nth-child(5) {
  background-color: red;
}

.step {
  width: 20%;
  height: 20px;
  display: inline-block;
}
  1. Grouping Elements: You can group elements using :nth-child() and apply styles to the grouped elements. For instance, to apply a border around every 3 elements:
div:nth-child(3n+1),
div:nth-child(3n+2),
div:nth-child(3n+3) {
  border: 1px solid black;
}
  1. Creating Zebra Stripes: You can create zebra stripes by targeting even and odd elements using :nth-child(even) and :nth-child(odd). For example:
tr:nth-child(odd) {
  background-color: lightgray;
}

tr:nth-child(even) {
  background-color: white;
}

Here are a few lesser-used tricks and techniques with the :nth-child() selector:

  1. Selecting Elements with a Repeat Pattern: You can select elements with a repeating pattern by using the :nth-child() selector with a formula. For example, to select elements with a pattern of 1-2-2, you can use:
div:nth-child(3n+1),
div:nth-child(3n+2) {
  /* CSS rules */
}
  1. Selecting Elements Excluding a Specific Position: You can select elements while excluding a specific position by using the :not() selector in combination with :nth-child(). For example, to select all elements except the first one:
div:not(:nth-child(1)) {
  /* CSS rules */
}
  1. Selecting Elements After a Specific Position: You can select elements that appear after a specific position using the :nth-child(n+x) selector. For example, to select elements after the third position:
div:nth-child(n+4) {
  /* CSS rules */
}
  1. Applying Styles to Elements in a Range: You can apply styles to elements within a range using :nth-child() with multiple formulas. For example, to select and style elements between the 3rd and 7th positions:
div:nth-child(n+3):nth-child(-n+7) {
  /* CSS rules */
}
  1. Applying Styles to Prime Number Positions: You can apply styles to elements that occupy prime number positions by using JavaScript in combination with :nth-child(). Here’s an example using JavaScript to add a class to prime number positions:
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
var divs = document.querySelectorAll('div');
Array.prototype.forEach.call(divs, function(div, index) {
  if (isPrime(index + 1)) {
    div.classList.add('prime');
  }
});

function isPrime(n) {
  if (n <= 1) {
    return false;
  }
  for (var i = 2; i < n; i++) {
    if (n % i === 0) {
      return false;
    }
  }
  return true;
}
div.prime {
  /* CSS rules */
}

These lesser-used tricks demonstrate the versatility of the :nth-child() selector and how it can be combined with other CSS techniques to achieve specific styling effects or target elements based on custom patterns.

Bonus Tips

Certainly! Here are some tips for using the :nth-child() selector effectively:

  1. Understand the Indexing: The :nth-child() selector uses 1-based indexing. The first element is considered :nth-child(1), the second is :nth-child(2), and so on. Keep this in mind when specifying the formula.

  2. Experiment and Test: It’s helpful to experiment with different formulas and test them in your specific HTML structure. Adjust the formula parameters (a, b, and the mathematical expression) to achieve the desired selection.

  3. Combine Multiple Selectors: You can combine the :nth-child() selector with other selectors to create more complex and specific targeting. For example, you can use it with class or attribute selectors to narrow down the selection.

  4. Use Negative Values: The :nth-child() selector also accepts negative values for a and b. Negative values select elements from the end of the list. For example, :nth-child(-n+3) selects the first three elements from the end.

  5. Leverage Mathematical Expressions: The formula within :nth-child() can be a mathematical expression. You can perform calculations and use variables to create dynamic selections. For example, :nth-child(2n + var(--offset)) allows you to use a CSS variable for the offset value.

  6. Be Aware of the Specificity: Keep in mind that the :nth-child() selector has its own specificity. If you’re using it with other selectors, ensure that the specificity of the entire selector is appropriate for the elements you want to target.

  7. Consider Browser Compatibility: The :nth-child() selector is supported in modern browsers, but older versions may have limited support. If you need to support older browsers, consider using JavaScript or server-side techniques instead.

  8. Document Your Selectors: When using complex :nth-child() selectors, it’s beneficial to document their purpose and intended selection. This helps with code maintenance and understanding when revisiting the code later.

By keeping these tips in mind, you can effectively use the :nth-child() selector to target and style elements in creative ways based on their position within their parent container.

Keep your curiosity going.Explore more CSS →
287 TUTORIALS · 22 TOPICSREADY