Jake Trent

Make a Repeating Style with nth-child

Repeating styles are made terse and simple using :nth-child.

Scenario

Let’s say I have a list of .box components and want to repeat the primary colors – red, yellow and blue – over and over for the length of the box list.

First, create as many boxes as you’d like:

<div class="boxes">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>
  <div class="box">4</div>
  <!-- more... -->
</div>

And style them as you’d like:

.boxes { /* ... */ }
.box { /* ... */ }

Identifying position in list

To identify the position of a box within the list, we can use :nth-child. This is a pseudo selector that can identify the index of an item in a group of sibling elements.

Alternately, :nth-of-type is similar and also has the ability to discount siblings that don’t match the selector (eg, select only p tags when there are also other sibling code tags).

Positions for the pattern

How do I specify that I want red first, then yellow, then blue and repeat?

First, count the distinct parts of the pattern. Here, there are 3 for the 3 colors.

Then setup 3 :nth-child selectors that start with 3n plus the position in the pattern that the selector applies to, starting with 1. Like this:

.box:nth-child(3n + 1) {
  background: red;
}
.box:nth-child(3n + 2) {
  background: yellow;
}
.box:nth-child(3n + 3) {
  background: blue;
}

Those are the steps. Count the distinct parts of the pattern; use :nth-child; set up a select for each part of the pattern.

See a working example.

Any other CSS tactics you use for repeating patterns?