There is a ::selection
pseudo class selector in CSS that allows you to style what content (mostly: text) looks like when it’s selected.
Say your website has pretty strong orange-colored branding, you could use this to extend the feel of that branding.

Like:
html {
--brandColor: orange;
}
::selection {
background-color: var(--brandColor);
}
Code language: CSS (css)
There is really only a couple of things you can set on ::selection
(see the allowable properties bit on MDN), which makes sense. You wouldn’t want to be changing font-size
on selection or anything like that as it would get messy quickly.
I was on the Lit documentation site the other day and highlighted some text and saw this:

At first I wasn’t even sure if it was intentional, but I sure thought it was neat! I figured it was just :nth-child()
trickery where you hang ::selection
off the end of it. Like:
:nth-child(5n)::selection {
background: oklch(70% 0.111 0 / 72.27%)
}
:nth-child(5n+1)::selection {
background: oklch(70% 0.111 40 / 72.27%)
}
:nth-child(5n+2)::selection {
background: oklch(70% 0.111 80 / 72.27%)
}
:nth-child(5n+3)::selection {
background: oklch(70% 0.111 120 / 72.27%)
}
:nth-child(5n+4)::selection {
background: oklch(70% 0.111 160 / 72.27%)
}
Code language: CSS (css)
So I made a demo of that and it works great:
No dice on iOS but it seems to work everywhere else.
I did ultimately poke at the Lit site with DevTools and saw their approach was basically what I thought it was going to be. Except a little more fancy as they are using color-mix()
with their primary colors and setting both the color
and background
.

If you’re thinking why not go full rainbow like with a linear-gradient()
like any sane thinking person is of course, unfortunately gradients are background-image
s, which are ignored here, with only background-color
being supported. 😭🌈