4

Just run into something surprising. If you do this:

footer::selection {
  color: white;
}

...it also removes the browser-default background-color for the highlighted text. It behaves as if you had also set background-color: transparent. (See demo below.)

Question: How can I retain or restore the system default text selection background-colour when setting a custom ::selection color?

(This answer lists various selection background colours used on different systems. But I don't just want to choose one, I want it to just be whatever the default is for the current system.)

Demo:

body {
  background: navy;
  color: gray;
}

p.custom::selection {
  color: white;
}
<p>Regular paragraph</p>
<p class="custom">Paragraph with text color changed in ::selection</p>
callum
  • 34,206
  • 35
  • 106
  • 163
  • What would you actually win in this situation, assuming you could do this - if my system’s background-color for selected text was set to white? – CBroe May 11 '21 at 11:11

1 Answers1

2

This behavior has been codified in the spec, as follows:

The UA must use its own highlight colors for ::selection only when neither color nor background-color has been specified by the author.

(This used to say "should" until last year, when it was changed to "must". There aren't any browsers implementing some version of ::selection that don't already follow this rule anyway.)

System colors are only exposed to CSS as user-defined values (which may or may not be just the system default), and not the system-defined defaults, so can't be known in advance. Therefore, as CBroe implies, this rule is in place to ensure that changing just one doesn't cause it to clash with the user-defined value for the other, causing contrast issues. The actual codification of this rule in the spec is for legacy reasons, but this rationale for browsers behaving like this in the first place is cited in discussions such as this one.

There are a number of standardized as well as non-standard system colors that exist, but the behavior of these varies wildly from browser to browser, and from platform to platform. Attempting to use any of these may have unexpected results, ranging from unexpected colors used, to being ignored by the browser altogether. Plus, as I mentioned, system colors are only exposed as user-defined values anyway. The CSSWG has discussed potential ways to improve this before; here's a recent conversation.

You are encouraged to apply a custom selection background color that complements your custom selection foreground color.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356