Rach Smith's Notes & Nuggets

Create a rainbow-coloured list with :nth-of-type()

note : development / css Added February 20, 2023

This is my favourite thing to do with the :nth-of-type() selector:

See the Pen rainbow list with :nth-of-type() by Rachel Smith (@rachsmith) on CodePen.

First, you need some colour values. I like to store them in CSS custom properties so it easy to order them the way you like later.

:root {
  --red: #f21332;
  --orange: #f27225;
  --pink: #e20b88;
  --yellow: #f2ad24;
  --green: #00b249;
  --blue: #1844b5;
  --purple: #a033b3;
}

Then you want to add an :nth-of-type declaration for each colour. The functional notation for each :nth-of-type is in the format of An+B, where A is the total number of colours you have, and B is the position of each colour. So as I have 7 colours, my functions look like 7n+1, 7n+2, 7n+3 and so on...

li:nth-of-type(7n + 1) {
  color: var(--red);
}

li:nth-of-type(7n + 2) {
  color: var(--orange);
}

li:nth-of-type(7n + 3) {
  color: var(--pink);
}

li:nth-of-type(7n + 4) {
  color: var(--yellow);
}

li:nth-of-type(7n + 5) {
  color: var(--green);
}

li:nth-of-type(7n + 6) {
  color: var(--blue);
}

li:nth-of-type(7n + 7) {
  color: var(--purple);
}

You can never have too many rainbows.

See the Pen rainbow list with :nth-of-type() by Rachel Smith (@rachsmith) on CodePen.

Comments

Comments are closed. You can still reply by email.

  • emily

    this is emily!!!
    i am a nerd.

  • Meiwah

    Gorgeous!