Create Rainbow Text with CSS: Three Different Methods
I really like adding rainbow text to my apps 🌈. There are three methods I usually use for this, so I thought I'd aggregate them into one post.
One method for adding a rainbow is to do stacked text shadows. In this example, I have 9 different text shadows all offset by 4px. For example, the first shadow is
-4px 4px #ef3550,. The first negative value places the shadow to the left of the letter. The second positive value puts the shadow 4px below the letter. Then, we have the color! The next shadow is
-8px 8px #f48fb1 which offsets the shadow by 4 additional pixels in each direction.
Another method is to make each letter a different color. For this one, there's a catch: you need to make each letter into its own HTML element. In this case, I used a
span. I then used the
:nth-child selector to apply different colors to each span.
For my portfolio site, I have 10 colors I rotate through -- so I use multiples of 10.
:nth-child(10n). I then need to add an offset to all but the first color --
:nth-child(10n + 2) for example. This will still apply the color to each 10th element, but starting at the second element instead of the first. This makes it so that the 2nd, 12th, 22nd and so on character have that color applied.
I would think about accessibility when using this method -- screen readers are going to read each letter as a letter instead of putting them together to form a word. So, you may want to hide the rainbow letters to the screen reader and then have another header on the page that is hidden for users reading the page.
The third method is to create a CSS gradient! I am hopeless at creating these by hand, so I use tools like this to help out.
Hope this will help add some fun 🌈s to your apps!