::selection
Changes the appearance of a piece of text selected by the user with the mouse or keyboard.
Example
#::selection {
background: #7c3aed;
color: #fff;
}
.code::selection {
background: #f59e0b;
color: #0c0c10;
}<p style="margin: 0 0 10px;">Select a piece of this paragraph, and then the code below.</p>
<pre class="code" style="margin: 0; padding: 10px 12px; border-radius: 10px; background: #18181b; font-size: 13px;">.card:hover { color: #fff; }</pre>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
#selector::selection { color: …; background-color: …; }Syntax variants
#- With no selector before the colons the style applies to the whole page. Select text in both paragraphs.
- A yellow, highlighter-like selection only in the paragraph with the
democlass. The second paragraph keeps the default.
Syntax variants in practice
#::selection
::selection { background: #7c3aed; color: #fff; }.demo::selection
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
#- user-selectLets you block or ease text selection by the user.
- colorSets the text colour and the default colour of borders, decorations and SVG icons that use currentcolor.
- background-colorSets the background colour of an element.
- ::placeholderStyles the hint text displayed in an empty input or textarea field.
- ::first-lineStyles the first line of text in a block element, regardless of how many words fit in it.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.