We're looking for a user researcher to understand the needs of developers and designers. Is this you or someone you know? Check out the post: https://mzl.la/2IGzdXS

This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The ::selection CSS pseudo-element applies styles to the portion of a document that has been highlighted by the user (such as with the mouse).

::selection {
  background: cyan;
}

Allowable properties

Only a small subset of CSS properties can be used in a rule with ::selection in its selector:

Note that, in particular, background-image is ignored.

Syntax

/* Firefox syntax */
::-moz-selection

::selection

Example

HTML

<div>This text has special styles when you highlight it.</div>
<p>Also try selecting text in this paragraph.</p>

CSS

/* Make selected text gold on a red background */
::-moz-selection {
  color: gold;
  background: red;
}

::selection {
  color: gold;
  background: red;
} 

/* Make selected text in a paragraph white on a blue background */
p::-moz-selection {
  color: white;
  background: blue;
}

p::selection {
  color: white;
  background: blue;
}

Result

Accessibility concerns

It is advisable to not override the operating system's default selected text style for purely aesthetic reasons, especially if the user has customized them to suit their needs. For people experiencing cognitive concerns or who are less technologically literate, this manipulation may affect their understanding of the functionality.  

If overridden, it is important to ensure that the contrast ratio between the color of the selected text and the background of the selected text is high enough that people experiencing low vision conditions will be able to read it when highlighted.

Color contrast ratio is determined by comparing the luminosity of the selected text and the selected text background color values. In order to meet current Web Content Accessibility Guidelines (WCAG), a ratio of 4.5:1 is required for text content and 3:1 for larger text such as headings. Large text is defined as 18.66px and bold or larger, or 24px or larger. 

Specifications

Specification Status Comment
CSS Pseudo-Elements Level 4
The definition of '::selection' in that specification.
Working Draft Initial definition.

Note: Though ::selection was present in drafts of CSS Selectors Level 3, it was removed during the Candidate Recommendation phase because its behavior was under-specified (especially with nested elements) and interoperability wasn't achieved (based on discussion in the W3C Style mailing list). It was brought back in Pseudo-Elements Level 4.

Browser compatibility

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support1 Yes

62

1 -moz-

99.51.1
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support ? ? Yes ? ? ? ?