Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS ::selection automatically swap color and background-color

I'm using the ::selection CSS construction. Say my text is written in black over a white background, but for some elements which are in written in blue, green or red for instance. I'd like that when selected, the color and background-color of the text are swaped: Normal text wound be white on black, red text would be white on red, etc...

Of course, I know how to do that by putting specific rules for each kind of text I have. But I wonder if there exists a simple way to do this automatically, that is without having to think to all the possible kind of texts I have.

like image 275
Bruno Avatar asked Oct 09 '22 11:10

Bruno


1 Answers

Unfortunately, there's no way to do this automatically: the closest thing we have to taking the specified font color is background-color: currentColor, but once you set color to any other value, currentColor will take that new value instead of the original.

Meaning, this rule:

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

Will actually set both the text color and the background color to white, because currentColor ends up computing to white, taking after the color: white declaration. This is regardless of whether you put it before or after the background-color declaration.

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

like image 134
BoltClock Avatar answered Oct 13 '22 11:10

BoltClock