Create a rainbow-coloured list with :nth-of-type()
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
Spencer
February 20, 2023 at 2:14 PM
This is awesome!
evan
February 28, 2023 at 9:39 AM
oh oh love love. brainy brilliant and beautiful!
Ian Stuart
February 28, 2023 at 12:10 PM
Very pretty.... much prettier than the version I have at https://musingsofacodegorilla.wordpress.com/2020/11/27/tables-with-banded-rows/
Sir Sally
February 28, 2023 at 2:51 PM
Hi there!
Thank you for sharing this code and fantastic example of :nth-of-type(). It's my favorite use, too, as well as my only use as of now :). Regarding the
Thank you very much.
Sir Sally
February 28, 2023 at 2:52 PM
The list dots. l i
Sir Sally
February 28, 2023 at 3:19 PM
Figured it out. Thanks again for the delightful design! style="list-style-type:none"
Rach Smith OP
March 1, 2023 at 11:34 PM
hi. Yes sorry, the code in this post just shows how to colour the
<li>
elements. But he styles for the rest of it are in the CodePen embedded above.emily
March 1, 2023 at 3:25 PM
this is emily!!!
i am a nerd.
Rach Smith OP
March 1, 2023 at 11:34 PM
girl same
Meiwah
March 28, 2023 at 3:13 AM
Gorgeous!
Leave a Comment
💯 Thanks for submitting your comment! It will appear here after it has been approved.