Use of `selection` Variant
Learn how to use the `selection` variant in TailwindCSS to style selected text and enhance user experience.
The selection
variant in TailwindCSS allows you to style the selected text in your application. This is useful for adding a unique touch to the selected text, enhancing the overall user experience.
Elevate your TailwindCSS skills with over 60 expert-crafted tips. Get early access to 31 actionable tips today and start building faster, smarter, and more confidently.
Usage
To implement the selection
variant:
Basic Usage
Apply the selection
variant to a parent element, preferably the body
element, to style the selected text:
<div class="selection:text-purple-700 selection:bg-purple-100 dark:selection:text-purple-200 dark:selection:bg-purple-500/15">
<p class="max-w-md text-body">Elevate your TailwindCSS skills with over 60 expert-crafted tips. Get early access to 31 actionable tips today and start building faster, smarter, and more confidently.</p>
</div>
Supported Properties
The selection
variant is a wrapper around the ::selection
pseudo-element in CSS. It supports the following properties:
color
:text-*
(color) utilitiesbackground-color
:bg-*
utilitiestext-decoration
:line-through
,underline
,no-underline
text-shadow
-webkit-text-stroke-color
,-webkit-text-fill-color
, and-webkit-text-stroke-width
Accessibility Warning
Don’t override selected text styles for purely aesthetic reasons — users can customize them to suit their needs. For people experiencing cognitive concerns or who are less technologically literate, unexpected changes to selection styles may hurt their understanding of the functionality.
If overridden, it is important to ensure that the contrast ratio between the text and background colors of the selection is high enough that people experiencing low vision conditions can read it.
Color contrast ratio is found by comparing the luminosity of the selected text and the selected text background colors. To meet current Web Content Accessibility Guidelines (WCAG), text content must have a contrast ratio of 4.5:1, or 3:1 for larger text such as headings. (WCAG defines large text as between 18.66px
and 24px
and bold
, or 24px
or larger.)
Content credit: MDN Web Docs