CSS Reference ยท Pseudo-elements
The ::selection pseudo-element
Reference for the CSS ::selection pseudo-element: change the color and background of text the user selects, with allowed properties and contrast advice.
The ::selection pseudo-element styles the part of a document that the user has highlighted, for example by dragging the mouse or pressing Shift with the arrow keys. By default the browser uses the system selection colors; with ::selection you can match them to your brand.
Only a handful of properties are allowed, because a selection must stay legible and cannot change the layout. Used on :root or *, the rule affects the whole page.
::selection { background: #ffd43b; color: #212529; }
Try it
Syntax
selector::selection { color: ...; background-color: ...; }
| Property | Value |
|---|---|
| Applies to | Any selectable text, and also image-like content in some browsers |
| Inherited | The pseudo-element inherits from its originating element, so values set on a parent are picked up |
| Animatable | No transitions run on selection |
Values
The pseudo-element takes no arguments. These properties are supported:
| Property | Description |
|---|---|
color |
Color of the selected text. |
background-color / background |
Fill behind the selected text (images are ignored). |
text-decoration and related |
Underline or line-through on the selected text. |
text-shadow |
A shadow on the selected text. |
-webkit-text-fill-color, stroke-color, fill-color |
Extra text paint properties in some browsers. |
Properties such as font-size, margin or padding have no effect.
Usage notes
- Keep contrast. The selected text must remain readable against the new background. Check the contrast of both colors, and avoid a background close to the page background.
- Don't override user choice blindly. Users with custom selection colors in their system rely on them; keep your colors strong and simple.
- Transparent backgrounds. If you set
coloryou should also setbackground, otherwise the pair may be unreadable in some themes. - One selector per rule. Older browsers drop a whole rule if one selector in a list is invalid. Write
::selectionand::-moz-selectionas separate rules if you must support old Firefox. - Text shadow carries over. If a parent has
text-shadow, selected text inherits it. Reset it withtext-shadow: none. - Input fields. It also applies to text selected inside inputs and textareas.
Browser support
Supported in every current browser. Only the properties listed above are honored.
Related
::highlight()โ custom highlights from JavaScript::spelling-errorcolor- Lesson: Pseudo-elements