::selection

Avatar of Katy DeCorah
Katy DeCorah on (Updated on )

UGURUS offers elite coaching and mentorship for agency owners looking to grow. Start with the free Agency Accelerator today.

Use your cursor select this sentence. Notice how as you select the text a background color fills the space? You can change the background color and color of selected text by styling ::selection. Styling this pseudo element is great for matching user-selected text to your sites color scheme.

p::selection {
  background: #fff;
  color: #ff0000;
}
Screenshot of selected text styled with the ::selection pseudo-element in CSS in white with a red background.

Take note that the double colon is necessary in the syntax for this pseudo element, despite that other pseudo-elements accept a single colon.

As seen above, you can style ::selection on individual elements. You can also style the entire page by dropping the bare pseudo-element in your stylesheet.

::selection { background: yellow; }

There are only three properties that ::selection will work with:

  • color
  • background (specifically the background-color, background-image longhand properties)
  • text-shadow

If you try to style ::selection with a property that’s not on the list, then that property will be ignored. It may be tricky seeing background in that list because the property will only render a color when used on ::selection and it won’t render a background image or gradient.

Also don’t try this:

p::-moz-selection,
p::selection { color: red; }

When browsers find a part of a select they don’t understand, they drop the entire thing, so this will fail all the time.

One of the most helpful uses for ::selection is turning off a text-shadow during selection. A text-shadow can clash with the selection’s background color and make the text difficult to read. Set text-shadow: none; to make text clear and easy to read during selection.

Fancy ::selection

Paired with Sass, or any other preprocessor, you can make really cool effects with ::selection. Select the text in the demo below:

You might notice the effect is not so smooth in some browsers. Let’s file that demo under: things that are possible, but probably just for fun.

Another dumb-but-fun little trick is revealing an image through selected text.

Browser support

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

ChromeFirefoxIEEdgeSafari
42*9123.1

Mobile / Tablet

Android ChromeAndroid FirefoxAndroidiOS Safari
1151154.4No

More information