CSS ::selection
Pseudo-Element
The ::selection
pseudo-element in CSS allows you to style the portion of text highlighted (selected) by the user. It can change the background color, text color, and a few other styles of the selected content.
1. Syntax
You can also target specific elements:
2. Example – Custom Selection Color
✅ When a user selects text, the background turns yellow and the text black.
3. Example – Styling Specific Elements
✅ This applies different highlight styles to <h1>
and <p>
elements.
4. What CSS Properties Can Be Used?
You CAN use:
✔ background-color
✔ color
You CANNOT use:
❌ border
, box-shadow
, cursor
, display
, text-decoration
, etc.
5. Example – Smooth Selection Effect
✅ A transparent blue selection effect for a modern look.
6. Browser Support
✅ Works in all modern browsers, but Internet Explorer does not support ::selection
.
📌 For better compatibility, use:
7. Best Practices
✔ Use a subtle selection color that contrasts well.
✔ Avoid making selected text too difficult to read.
✔ Test in different browsers for consistency.