Skip to main content

jul 21, 2023

🔗 Text selection color

Utilities is one of those words that make web developers recall when you needed complex tricks to have a rounded button or a nice gradient. This is a collection of utilities and snippets I created and refined during my job as front-end developer

Today browsers got a lot better, tailwind and javascript framework made life easier and utilities snippets are not that common anymore. But with web development constantly evolving, new opportunities arise to learn new tricks and get some new tools in the toolbox.

Adding the feature of highlighting words with a custom on-brand color, different from the default one, is one of them and can be a nice touch to add when polishing a new website.

It's very easy to add a ::selection highlight color to the CSS. Just add the following code to the CSS file:

::selection,
::target-text,
::search-text {
	background: yellow;
	color: black;
}

::target-text and ::search-text are newer pseudo-elements that are used when the user clicks on a link containing Text fragments or searches for a word on the page, respectively. They are not supported in all browsers, but it's a good idea to add them to the CSS file.

The most important thing to keep in mind when working with this feature is to make sure the color contrast is high enough, for accessibility reasons. Generally you want to use a light highlight color, but if anywhere in the website you have a light text, you should use a dark highlight color instead.

# Resources