iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📝

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.

Example of using ::selection

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

  • color
  • background-color
  • text-decoration
  • text-shadow
  • cursor
  • caret-color
  • outline
  • text-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