Changing the Text Selection Color Using CSS

Is there any way to change background color of ::selection (selected text) using JavaScript?

In general where it's not possible to directly change pseudo element settings via JS it is possible to set CSS variables using JS.

So if you have something like this in your stylesheet:

::selection {
background-color: var(--selcolor);
}

and something like this in your JS:

   element.style.setProperty('--selcolor', selcolor)

it will work.

Here's small example. It changes the selection color variable in the body:

function selChange(color) {
document.body.style.setProperty('--selcolor', color);
}
body {
--selcolor: yellow;
}

::selection {
background-color: var(--selcolor);
}
<button onclick="selChange('cyan');">Cyan</button>
<button onclick="selChange('magenta');">Magenta</button>
<button onclick="selChange('yellow');">Yellow</button>
<p>Highlight some of this text, then click a color and highlight some text...</p>

Change selected text color easily?

CSS custom properties / CSS Variables will be a better approach.

You can do something like this:

const root = document.documentElement;
const darkMode = document.getElementById("darkMode");

darkMode.addEventListener("click", () => {
root.style.setProperty("--selectionBG", "blueviolet");
root.style.setProperty("--selectionColor", "turquoise");

document.body.style.backgroundColor = "#111";
document.body.style.color = "#eee";
});
:root {
--selectionBG: cyan;
--selectionColor: navy;
}

::selection {
color: var(--selectionColor);
background: var(--selectionBG);
}
<body>
<button id="darkMode">Dark Mode</button>

<h1>Lorem ipsum dolor sit amet consectetur adipisicing elit. Amet natus quia minus cum.</h1>
</body>

how to change the text selection background color

You can use certain CSS selectors to change CSS properties on selected text. (I tested this and it worked in Firefox, Safari, Chrome, and even Konqueror, but not IE). Example:

*::selection {
background: #cc0000;
color: #ffffff;
}
*::-moz-selection {
background: #cc0000;
color: #ffffff;
}
*::-webkit-selection {
background: #cc0000;
color: #ffffff;
}

You have to specify each selector separately or else it doesn't work (I guess the CSS parser stops processing a selector if it encounters an error). This changes the background color of the selected text to dark red and the color to white (and any other CSS you want to change). This doesn't have great cross-browser support (doesn't work in IE, and probably not Opera, either), but I think it is the only solution possible without some kind of complicated, buggy JavaScript script.

More info: http://www.quirksmode.org/css/selection.html

How Do You Fix the Darkened Text Selection Color in Safari? - CSS

this issue described here

For now you can make your background-color 99% opacity

::selection {
background-color: rgba(0, 50, 0, 0.99);
color: #fff8dc;
}

Permanently change selected text background color

You need to add event listener in javascript and when a text is selected at that time need to change the color like below

function logSelection(event) {
// Get Selection
sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
// Set design mode to on
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// Colorize text
document.execCommand("ForeColor", false, "red");
// Set design mode to off
document.designMode = "off";
}

const input = document.querySelector('input');
input.addEventListener('select', logSelection);

How to change the highlight color of selected text in a textarea, using selection range?

I don't understand exactly what you want.

Did you want an answer like the code below?

https://codepen.io/jyh7a/pen/xxpLMZZ

HTML

<input type="text" id="text-box" size="20" value="Mozilla">
<button onclick="selectText()">Select text</button>

<hr/>

<textarea rows="6" cols="40">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Porro maxime excepturi autem nostrum minus quae magni, esse optio ab, dolor ut iste earum sapiente molestiae nihil totam rem ipsam officia?</textarea>

<hr/>

<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Porro maxime excepturi autem nostrum minus quae magni, esse optio ab, dolor ut iste earum sapiente molestiae nihil totam rem ipsam officia?</p>

CSS

::selection {
background-color: rgba(255,0,0,0.2);
}

JS

function selectText() {

const input = document.getElementById('text-box');
input.focus();
input.setSelectionRange(2, 5);

setTimeout(() => {
const textarea = document.querySelector('textarea');
textarea.focus();
textarea.setSelectionRange(0, 20);
}, 1000)


// // ERROR!
// // setSelectionRange function only use HTMLInputElements
// const p = document.querySelector('p');
// p.setSelectionRange(0, 20);
}

I searched for setSelectionRange

I made the above example by looking at the MDN official documentation.

(Link: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange )

Hope the above code was helpful to you.

How to set custom ::selection style but keep the browser-default text selection color?

This behavior has been codified in the spec, as follows:

The UA must use its own highlight colors for ::selection only when neither color nor background-color has been specified by the author.

(This used to say "should" until last year, when it was changed to "must". There aren't any browsers implementing some version of ::selection that don't already follow this rule anyway.)

System colors are only exposed to CSS as user-defined values (which may or may not be just the system default), and not the system-defined defaults, so can't be known in advance. Therefore, as CBroe implies, this rule is in place to ensure that changing just one doesn't cause it to clash with the user-defined value for the other, causing contrast issues. The actual codification of this rule in the spec is for legacy reasons, but this rationale for browsers behaving like this in the first place is cited in discussions such as this one.

There are a number of standardized as well as non-standard system colors that exist, but the behavior of these varies wildly from browser to browser, and from platform to platform. Attempting to use any of these may have unexpected results, ranging from unexpected colors used, to being ignored by the browser altogether. Plus, as I mentioned, system colors are only exposed as user-defined values anyway. The CSSWG has discussed potential ways to improve this before; here's a recent conversation.

You are encouraged to apply a custom selection background color that complements your custom selection foreground color.

Changing the highlight color when selecting text in an HTML text input

Thanks for the links, but it does seem as if the actual text highlighting just isn't exposed.

As far as the actual issue at hand, I ended up opting for a different approach by eliminating the need for a text input altogether and using innerHTML with some JavaScript. Not only does it get around the text highlighting, it actually looks much cleaner.

This granular of a tweak to an HTML form control is just another good argument for eliminating form controls altogether. Haha!



Related Topics



Leave a reply



Submit