CSS :nth-child selector with a grid

The :nth-child CSS selector (or pseudo-class) has a number of uses. We’ve looked at some basic CSS :nth-child selector techniques before. Now, we’re going to look at some examples with grids, using some of the same selector patterns and some different ones.

We apply a variety of styles to show some different effects.

Setting Up

The examples that follow use this HTML snippet:

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
</ul>

We use the following CSS to display the list as a grid:

ul {
  list-style-type: none;
  padding: 0.2em;
}
ul li {
  width: 27%;
  float: left;
}

Examples

Evens

Example with every second item, started from the second, which means the evenly numbered ones (pink background):

li:nth-child(2n) {
  background-color: pink;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Odds

Example with every second item, starting from the first, which means the oddly-numbered ones (bold text):

li:nth-child(2n+1) {
  font-weight: bold;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Specific Numbers

Example with a numbered element, in this case the second (bold text and pink background):

li:nth-child(2) {
  background-color: pink;
  font-weight: bold;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Spans of Elements

Example with a span of elements from the beginning to the second element inclusive (italic text and yellow background):

li:nth-child(-n+2) {
  background-color: yellow;
  font-style: italic;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Example with a span of elements from the second to the last inclusive (bold text and yellow background):

li:nth-child(n+2) {
  background-color: yellow;
  font-weight: bold;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

At Intervals

Example with every third item starting from the third, which means the last column on a 3x3 grid (light blue background):

li:nth-child(3n) {
  background-color: lightblue;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Example with every third item starting from the first, which means the first column on a 3x3 grid (light blue background):

li:nth-child(3n+1) {
  background-color: lightblue;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Example with every third item starting from the second, which means the middle column on a 3x3 grid (light blue background):

li:nth-child(3n+2) {
  background-color: lightblue;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Read more

For more documentation and examples, see:

Tags: