點燈坊

うまく使いさえすれば、時間はいつも十分にある

Using selection to Style the Selected Text

Sam Xiao's Avatar 2022-01-29

We can use selection modifier to style the selected text.

Version

TailwindCSS 3.0

selection

selection000

When selecting the text, text color and background color are changed.

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://unpkg.com/alpinejs" defer></script>
  <script src="https://cdn.tailwindcss.com"></script>
  <title>Alpine</title>
</head>
<body>
  <p class="selection:bg-teal-500 selection:text-white">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
    incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
    exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
    Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
    mollit anim id est laborum.
  </p>
</body>
</html>

Line 11

<p class="selection:bg-teal-500 selection:text-white"></p>
  • selection:bg-teal-500 : apply bg-teal-500 on selection modifier, which sets background color.
  • selection:text-white : apply text-white on selection modifier, which sets text color.

Conclusion

  • By using selection modifier, we can style the selected text by utilities

Reference

TailwindCSS, Highlighted text