3

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>
JueK3y
  • 267
  • 9
  • 22

1 Answers1

4

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>
  • Thank you, that helps me a lot :) To underline only the part that is also marked, you most likely need JavaScript then, I guess – JueK3y Jul 16 '21 at 07:58
  • 1
    @JueK3y indeed because underline applies to the entire node, in order to accomplish this (and any fancy custom styling like the gradient you want) you could wrap the selected text with an inline element (use the ‘mark’ tag and style it with a class). The JS solution is described in the following SO: https://stackoverflow.com/questions/6328718/how-to-wrap-surround-highlighted-text-with-an-element/6328906#6328906 – Peter van der Steen Jul 16 '21 at 09:10