Styling Highlighted Text with Tailwind CSS
Styling Highlighted Text with Tailwind CSS
This tutorial is part of our Learn Tailwind CSS Guide

Styling Highlighted Text with Tailwind CSS

Chris Sev's Profile
Chris Sevon Jun 21, 2021

Tailwind v2.2 brings us cool new features like styling highlighted text.

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:

html<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.
</p>

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

html<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 Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)