CSS :: selection automatically changes color and background color

I am using the CSS ::selection construct. Say my text is written in black over a white background, but for some elements that are written in blue, green, or red, for example. I would like this to be selected, the color and background color of the text are exchanged: Plain text hurts white on black, red text is white on red, etc.

Of course, I know how to do this by introducing specific rules for each type of text that I have. But I wonder if there is a simple way to do this automatically, that is, I don’t need to think about all the possible types of texts that I have.

+4
source share
1 answer

Unfortunately, there is no way to do this automatically: the closest to what we need to take the specified font color is background-color: currentColor , but as soon as you set color to any other value, currentColor will take a new value instead of the original.

Meaning, this rule:

 ::selection { background-color: currentColor; color: white; } 

Actually set the text color and background color to white, because currentColor finishes the calculation to white , accepting color: white after the declaration. This is regardless of whether you put it before or after the background-color declaration.

Here's an interactive script to show you what I mean.

+4
source

Source: https://habr.com/ru/post/1399949/


All Articles