CSS pseudo-elementPseudo-elements

::selection

Changes the appearance of a piece of text selected by the user with the mouse or keyboard.

On this page

Example

#
CSS
::selection {
  background: #7c3aed;
  color: #fff;
}

.code::selection {
  background: #f59e0b;
  color: #0c0c10;
}
Preview

Each part has a different selection colour: the paragraph is purple and the code block is orange.

Definition and usage

#

The ::selection pseudo-element targets the part of the document that the user has selected, for example by dragging the cursor across text or double-clicking a word. You can change the selection’s background colour and text colour to match the style of your site.

The list of supported properties is short: mainly color and background-color, and according to the specification also text decoration and text shadow. Margins, borders, or font changes are ignored, because a selection must not change the layout of the text.

A rule with nothing before the colons (::selection) applies to the whole page, and with a selector, for example .code::selection, only in the chosen element. Keep a readable contrast between the selection background and the text, and don’t set a transparent background, or the user will lose the information about what was selected.

Syntax

#
Syntax
selector::selection { color: …; background-color: …; }

Syntax variants

#
  • ::selection

    With no selector before the colons the style applies to the whole page. Select text in both paragraphs.
  • .demo::selection

    A yellow, highlighter-like selection only in the paragraph with the demo class. The second paragraph keeps the default.

Syntax variants in practice

#

::selection

With no selector before the colons the style applies to the whole page. Select text in both paragraphs.
::selection { background: #7c3aed; color: #fff; }

.demo::selection

A yellow, highlighter-like selection only in the paragraph with the demo class. The second paragraph keeps the default.
.demo::selection { background: #fde047; color: #0c0c10; }

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Keep a clear contrast between the text and the selection background. Selected text must be as readable as the rest.
  • Don’t hide the selection with a transparent background. If text shouldn’t be selectable, for example in a button, use user-select: none.

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.