What it is and why to use it
::selection styles supported aspects of text selected by the user. It is useful for making copied passages fit a site’s theme while remaining readable. Selection highlighting is a special painting layer rather than an ordinary element box.
Common mistakes and limitations
Only a limited set of properties applies to selection highlights. User agents and forced-colors settings may override the palette. Do not suppress selection or make selected text unreadable just to keep a visual theme.
Try the example
The example pairs editable CSS with its own HTML preview. Run it, then change one declaration at a time and compare the result. Locally, put the CSS in a style element in the document head or in an external stylesheet linked from the HTML. Feature support varies by browser and version; use the linked reference and a useful fallback where needed.
HTML used by this example
<p class="passage">Select part of this passage to see the custom selection colours. Reading and copying should remain straightforward.</p>Syntax
::selection { background: #bfdbfe; color: #0f172a; }Examples
Text Selection Colours with ::selection
Run the CSS against the supplied HTML, then experiment with the values.
.passage { padding: 1rem; line-height: 1.6; color: #0f172a; background: white; }
.passage::selection, .passage *::selection { background: #bfdbfe; color: #0f172a; }- The paragraph has a normal foreground and background before selection.
- Dragging across text reveals the chosen selection palette.
- The descendant rule includes nested text elements if they are added later. This is useful for articles where users frequently select and copy passages.
HTML used by this example
<div class="demo"><p class="passage">Select part of this passage to see the custom selection colours. Reading and copying should remain straightforward.</p></div>Best practices
- Only a limited set of properties applies to selection highlights. User agents and forced-colors settings may override the palette. Do not suppress selection or make selected text unreadable just to keep a visual theme.
- Inspect the relevant browser reference and test the browsers used by your audience.
Runtime & versions
Web browsers. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
CSS specifications (modules)