Working with different background colors for web pages, you may run into problems when the default background color for text selection matches with web page color. This is very annoying for the users because the selected text doesn’t get highlighted. TailwindCSS provides :selection
modifier to change the background of selected text.
Using :selection
Modifier in TailwindCSS
You can use :selection
modifier to change both, the background and text color when the user selects some text on the page. The following code example demonstrates how to use :selection
in TailwindCSS. Here is an online demo of the example.
1 2 3 4 5 6 7 8 9 |
<div class="flex h-screen justify-center items-center flex-col text-white bg-cyan-900 text-2xl"> <p class="selection:text-gray-100 selection:bg-orange-800 max-w-xl "> Lorem ipsum dolor sit, amet consectetur adipisicing elit. Sint aspernatur repellat, maiores iure delectus quos? Exercitationem earum, adipisci voluptatibus error quos maiores nemo soluta, sequi distinctio quaerat cupiditate? Ut, rerum. </p> </div> |
The above code will change the selected text background color like below.
Conclusion
The :selection
modifier helps to change the background as well as the text color of the selected text. This is useful when you are using different background colors on the web page and the default selection color doesn’t work well.