::selection
Learn text selection styles with ::selection.
What is ::selection?
The ::selection pseudo-element styles text the user highlights with the mouse or keyboard. Writing ::selection { background: navy; color: white; } turns every selected range into white text on a navy background.
This pseudo-element responds to a user action rather than to an element. It can also be combined with a selector: p::selection only colors selections made inside paragraphs.
Allowed properties
::selection does not accept every property; browsers allow only a few. color, background-color, text-decoration and shadows work; margin, padding or display are ignored.
The limit is deliberate: a selection is a temporary emphasis and must not break layout. So only visual emphasis is allowed; properties that change box size are blocked.
Exercise Set selection colors
Write a ::selection pseudo-element and set background: navy and color: white inside. That way, when the user selects text on the page, the selection becomes white on a navy background.
Show example solution
/* set the page selection color */
::selection {
background: navy;
color: white;
}
Test yourself
-
Which property works inside ::selection?
::selection { /* ? */ }- display
- margin
- position
- background-color
Show answer
background-color — Correct. background-color paints the selection's background; it is one of the allowed ::selection properties.
-
Write the ::selection block
____ { background: navy; color: white; }Show answer
::selection { background: navy; color: white; } -
Match each pseudo-element to what it styles
- ::selection
- Selected text
- ::first-letter
- First letter
- ::placeholder
- Input hint
- ::after
- After content