skip to Main Content

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


  1. 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:

    document.addEventListener('mouseup', function() {
        var selectedText = window.getSelection().toString();
        var selectionColor = getComputedStyle(document.documentElement).getPropertyValue('--selection-color');
    
        if (selectedText.length > 0) {
            document.execCommand('styleWithCSS', false, true);
            document.execCommand('foreColor', false, selectionColor);
        }
    });
    

    Here, we listen for the mouseup event and get the selected text. Then we retrieve the value of the --selection-color custom property using getComputedStyle(). Finally, we are using document.execCommand() to apply the selected color to the text.

    Login or Signup to reply.
  2. You please try with this

    :root {
      --selection-color: green;
    }
    
    ::selection {
      background-color: transparent;
    }
    
    p::after {
      content: "";
      background-color: var(--selection-color, red);
      opacity: 0.3;
      pointer-events: none;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      z-index: -1;
    }
    
    p::selection {
      background-color: var(--selection-color, red);
      color: white;
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search