CSS ::selection: Customize Text Selection Colors
The CSS ::selection pseudo-element allows web developers
to override the browser's default highlight styling when a user selects
text on a webpage. By defining custom text and background colors, you
can align text highlights with your website’s brand palette and improve
visual hierarchy. This guide explains how the ::selection
pseudo-element works, the specific properties it supports, how to target
text globally or within specific elements, and best practices for
accessibility.
How the
::selection Pseudo-Element Works
When users highlight text with a mouse or touch gesture, browsers
apply a default highlight—typically a blue background with white or
inverted text. The ::selection pseudo-element intercepts
this action and applies your custom styles to the highlighted portion of
the document.
Global Selection Styling
To apply a uniform highlight color across your entire website, attach
::selection directly without a preceding selector:
::selection {
background-color: #ffeb3b; /* Highlight background */
color: #000000; /* Text color */
}With this rule, any text highlighted anywhere on the page will adopt a yellow background with black text.
Scoped Selection Styling
You can also target specific elements or classes to provide contextual styling. For instance, you might want blockquotes or headings to feature a different highlight color than standard body paragraphs:
/* Custom selection for headings */
h1::selection,
h2::selection,
h3::selection {
background-color: #2b6cb0;
color: #ffffff;
}
/* Custom selection for a specific class */
.callout::selection {
background-color: #e53e3e;
color: #ffffff;
}Supported Properties
Browsers restrict which CSS properties can be used inside
::selection for security and performance reasons (to
prevent layout thrashing while selecting).
Only the following properties are valid within
::selection:
color(text color)background-color(selection background color)text-decorationand its associated properties (text-decoration-line,text-decoration-color, etc.)text-shadowstroke-color,fill-color, andstroke-width(for SVG text)
Properties that alter the box model—such as font-size,
margin, padding, display, or
background-image—are ignored by browsers inside
::selection.
Accessibility and Contrast
When styling selection colors, contrast is critical. If the contrast
ratio between the text color and the selection
background-color is too low, the highlighted text will
become unreadable for users, especially those with visual
impairments.
Always test your custom colors against Web Content Accessibility Guidelines (WCAG) to ensure a minimum contrast ratio of:
- 4.5:1 for regular body text.
- 3:1 for large text (18pt or larger, or 14pt bold).
If you only define a background-color without specifying
a color, the browser will attempt to use the existing text
color, which may result in poor contrast against your custom highlight
background. Always define both properties together.