How to Use ::selection in CSS to Style Text Selection
Use the
::selection pseudo-element in CSS to style the part of the text a user highlights. You can change properties like background-color and color to customize the selection appearance.Syntax
The ::selection pseudo-element targets the portion of an element that the user selects (highlights) with the mouse or keyboard. You write it by appending ::selection to a selector.
Inside the curly braces, you define styles like background-color or color that apply only to the selected text.
css
selector::selection {
property: value;
/* example: background-color: yellow; color: black; */
}Example
This example changes the background color to blue and text color to white when you select text inside a paragraph.
css
p::selection {
background-color: #007BFF;
color: white;
}
/* HTML to test */
<p>Select this text to see the custom selection style.</p>Output
A paragraph of text where the selected portion has a blue background and white text color.
Common Pitfalls
- Not all CSS properties work with
::selection; only a few likecolor,background-color,text-shadow, andcursorare supported. - Using single colon
:selectionis allowed but::selectionis the modern standard. - Applying
::selectionto elements that don’t contain selectable text will have no visible effect.
css
/* Wrong: Using unsupported property */ ::selection { font-size: 20px; /* This will not work */ } /* Correct: Use supported properties only */ ::selection { background-color: yellow; color: black; }
Quick Reference
| Property | Supported in ::selection | Description |
|---|---|---|
| background-color | Yes | Changes the background color of selected text |
| color | Yes | Changes the text color of selected text |
| text-shadow | Yes | Adds shadow to selected text |
| cursor | Yes | Changes the mouse cursor when hovering selected text |
| font-size | No | Does not affect selected text |
| border | No | Not supported on selection |
Key Takeaways
Use
::selection to style the look of highlighted text in CSS.Only a few properties like
color and background-color work with ::selection.Always use double colon
::selection for modern CSS, but single colon works in some browsers.Apply
::selection to elements containing selectable text for visible effect.Test your styles by selecting text in the browser to see the changes live.