This used to work, but now this code no longer works, not sure what happened.
I have a theme with various colors set by CSS custom props. I use the theme to set the color of text when it is selected. I am using Chrome With Chrome Version 114.0.5735.198 (Official Build) (64-bit), on Ubuntu 22.04, x-server with i3 window manager, Nvidia graphics.
:root {
--selection-color: green;
}
::selection {
color: white;
background: var(--selection-color, red);
}
<p>Some text to select with your cursor<br> It should be green if the custom prop is working correctly, red if not</p>
The selected text is supposed to be green.
2
Answers
You’re trying to use CSS custom properties to set the color of selected text on your website. but the code is not working as expected in Chrome 113.
CSS
::selection
pseudo-element was widely supported in older versions of browsers but was later removed from the CSS Selectors Level 4 specification, which might be the reason it’s no longer working. It’s possible that Chrome 113 has removed support for the::selection
pseudo-element.To achieve the desired effect, you can try using JavaScript to dynamically update the selected text’s color. Here’s an example:
Here, we listen for the
mouseup
event and get the selected text. Then we retrieve the value of the--selection-color
custom property usinggetComputedStyle()
. Finally, we are usingdocument.execCommand()
to apply the selected color to the text.You please try with this