iTranslated by AI
How to Change Text Selection Background Color with CSS
By using the CSS pseudo-element ::selection, you can change the color of the selected portion of text. It is available in major modern browsers, including IE11.
The image above is an example of applying the following CSS.
p::selection {
background-color: yellow;
}
I have also prepared an actual sample.
Only some properties can be specified with ::selection
By the way, you cannot change the weight of the selected text, such as with .example::selection { font-weight: bold; }. This is because there are limitations on the CSS properties that can be used within ::selection.
Properties that can be used with ::selection
colorbackground-colortext-decorationtext-shadowcursorcaret-coloroutlinetext-emphasis-color
For example, background-image, font-weight, and font-size cannot be used. This is a reasonable specification. For instance, if font-weight could be specified, the width of the selected font would change, causing the text to reflow and break lines abruptly.
Basically, it is best to stick to only specifying background-color and color within ::selection.
Discussion