0
0
CssHow-ToBeginner · 3 min read

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 like color, background-color, text-shadow, and cursor are supported.
  • Using single colon :selection is allowed but ::selection is the modern standard.
  • Applying ::selection to 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

PropertySupported in ::selectionDescription
background-colorYesChanges the background color of selected text
colorYesChanges the text color of selected text
text-shadowYesAdds shadow to selected text
cursorYesChanges the mouse cursor when hovering selected text
font-sizeNoDoes not affect selected text
borderNoNot 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.