Skip Navigation

Scott Spence

Change Text Highlight Color with Tailwind CSS

3 min read
Hey! Thanks for stopping by! Just a word of warning, this post is almost 2 years old, . If there's technical information in here it's more than likely out of date.

How to change the highlight color of text on the page? Here’s the situation! I wanted to change the text highlight color to a different colour than the default blue on my site.

To change the default text highlight color in a Tailwind CSS project you can add the ::selection selector to the Tailwind file that has the @tailwind directives in it (usually named app.css or tailwind.css).

In the selector I can add in the colour that I want to use.

::selection {
  background: red;
}

That’s setting it to one colour though, and I want to change this along with the primary colour of my theme.

So now when some text is highlighted it shows the theme colour.

As a side note, my site did have quite a big configuration file for the scrollbar. You can take a look at what my app.css file used to look like by clicking the button.

I’m mentioning this because I was using my own CSS variables for the theme change. It wasn’t until I messaged the massively helpful Pouya (daisyUI creator) on Twitter that I realized that I could use daisyUI CSS variables.

Here’s how the chat went:

Hey man! If I want to change the selection colors in Tailwind I’ll need to use the daisyUI hardcoded theme colors right?

Hey, if the color exists in theme already, you can just use that variable

Over on daisyUI you can see all the variables. for example --s is for secondary color

and they’re all HSL values

so they should be used like hsl(var(--s))

whaaaa??

So I can use a variable instead of hardcoding in all the values??

Yeah 😅 all colors are CSS variables already

Sweet! I didn’t know they were accessible in the main tailwind.css file. Thanks! 🙏

Pouya mentioned that I can get the daisyUI colours from the colors section of the daisyUI docs.

So with this information I set about making the ::selection selector in my app.css file. The CSS looks like this for it now:

::selection {
  color: hsl(var(--pc));
  background: hsl(var(--p));
}

With this new information I reduced the app.css file in my project from 178 to 57 lines of code! 😅

You can take a look at the file here (by clicking the button) with some additional CSS removed. Or you can check out the file over on GitHub.

That’s it!

If you want to Change Browser Scrollbar Colour with Tailwind CSS then check out the post where I go into more detail about that.

Also there’s a post on Gradient animations with Tailwind CSS and SvelteKit that you can check out.

Hope you find it useful, I know I did! 😊

There's a reactions leaderboard you can check out too.

Copyright © 2017 - 2024 - All rights reserved Scott Spence