CSS ::selection Pseudo Element

CSS ::selection Pseudo Element

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

::selection { property: value; }

You can also target specific elements:

p::selection { background-color: yellow; color: black; }

2. Example – Custom Selection Color

::selection { background-color: #ffcc00; color: black; }

✅ When a user selects text, the background turns yellow and the text black.

3. Example – Styling Specific Elements

h1::selection { background-color: red; color: white; } p::selection { background-color: lightblue; color: darkblue; }

✅ 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

::selection { background-color: rgba(0, 150, 255, 0.5); color: white; }

✅ 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:

::-moz-selection { background: orange; } /* For Firefox */ ::selection { background: orange; }

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.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close