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>