Underline text with line when selected

Viewed 1082

The idea:
I want to have the text underlined (preferably in a color gradient like here) when selecting a text section instead of changing the background. According to Mozilla text-decoration is possible, so also text-decoration: underline.

The problem:
(text-decoration with ::selection does not work for me (Chrome & Edge) - solved).

The solution idea:
Is it at all possible to underline the text as a gradient when making a selection (in CSS)? One idea of mine is to use JavaScript to see if the text is selected and then add an id="underline" or so between the text, which then contains the CSS code for the gradient line.


Progress:
The whole thing is not achieved with pure CSS. I have now changed the code, so that when a selection is also the text is suitably underlined.

Problem with the progress:
The line remains even after clicking away the selection.

The current code:

    function wrapSelectedText() {       
        var selectedText = window.getSelection().getRangeAt(0);

        var selection = window.getSelection().getRangeAt(0);
        var selectedText = selection.extractContents();
        var span = document.createElement("span");
        /* Styling */
        span.style.backgroundImage = "linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%)";
        span.style.backgroundRepeat = "no-repeat";
        span.style.backgroundSize = "100% 0.2em";
        span.style.backgroundPosition = "0 88%";

        span.appendChild(selectedText);
        selection.insertNode(span);
    }

    document.onmouseup = document.onkeyup = document.onselectionchange = function() {
        wrapSelectedText();
    };
::selection {
  background: none;
}
<p>This is an example text.</p>

1 Answers

The text-decoration needs to exist already on the element, by defining text-decoration: underline overline transparent; on the p element it does work.

::selection {
  background: yellowgreen; /* To check if the text is selected */
  text-decoration: underline overline #FF3028; /* Only works on elements that have the same decoration properties set already */
}

p {
  color: black;
  font-size: 18px;
  text-decoration: underline overline transparent;
}
<p>This is an example text.</p>

Related