Styling Highlighted Text with Tailwind CSS

Tailwind just released version 2.2 which brings some fun new features thanks to the new JIT (Just-in-Time) mode.

JIT mode enabled Tailwind to calculate values on the fly. For instance, we could set specific widths with: w-[200px] and specific colors with bg-[#c00c00].

Now we have the ability to style highlighted text. This is done in CSS using the ::selection pseudo selector.

Note: This feature requires Tailwind 2.2+ and JIT mode enabled.

Here's making highlighted text have a yellow background:

Styling Highlighted Text with Tailwind CSS

To style highlighted text with Tailwind, we'll use the selection: prefix.

You can turn the background of highlighted text to pink with:

<p class="selection:bg-pink-200">
  After nearly a grueling hour of warfare with neither man scoring a fall, Hart
  locked in the Sharpshooter, his signature submission hold. As Michaels
  screamed in pain, the crowd were certain that Hart was about to walk away from
  WrestleMania XII as the still-World Heavyweight Champion.

Let's say we want this site to have a yellow background when you highlight the text. We can do the following:

<div class="selection:bg-yellow-300 selection:text-black">way cool!</div>

I was going to embed a CodePen here, but this feature requires the Tailwind JIT mode to be turned on in your tailwind.config.js.

Here is a Tailwind Play link to see it in action.

JIT mode is adding some more fun stuff like before and after variants and also first letter and first line variants.

If you enjoyed this tutorial, We also have a Getting Started with Tailwind course.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created which was acquired.