Change text selection colors with CSS ::selection

Use CSS ::selection to set background-color and color for selected text. The style appears while the text is selected and needs no JavaScript.

Try a complete selection color example

Save the code as selection-color.html and open it. Select part of a line in each paragraph and compare the text and background colors. Clear the selection to see the original text colors again.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Compare text selection colors</title>
  <style>
    body { margin: 20px; font: 16px/1.6 system-ui, sans-serif; color: #203348; }
    h1 { font-size: 24px; }
    main { max-width: 650px; }
    p { padding: 16px; border: 1px solid #9eafbf; line-height: 1.8; }
    ::selection { background-color: #ffe6a7; color: #4a2a00; text-shadow: none; }
    .special::selection { background-color: #153e6b; color: #fff; }
  </style>
</head>
<body>
<main>
  <h1>Compare text selection colors</h1>
  <p class="normal">Select part of this paragraph to see dark brown text on a pale yellow background.</p>
  <p class="special">Select part of this paragraph to see white text on a dark blue background.</p>
</main>
</body>
</html>

In the first paragraph, selected text is dark brown on pale yellow. In the paragraph with the special class, it is white on dark blue. Selecting only part of either paragraph makes it easy to compare the highlight with the surrounding text.

Limit the style to a paragraph or section

The ::selection rule supplies the page-wide default. .special::selection gives the second paragraph its own colors. To target only paragraphs in your article, use the container selector in a rule such as .article-content p::selection. If a link inside a paragraph has its own selection style, inspect that rule as well. See CSS Pseudo-Elements · Cascading Highlight Styles.

Change only the background-color in .special::selection to #156754 and select text again. The second highlight turns green, while the first stays yellow. Restore the original blue after comparing. If you remove both selection rules from the example, the browser uses its default selection colors.

Check supported properties and contrast

Selection highlights support a limited set of properties, including color, background-color, and text-shadow. padding cannot enlarge the highlighted area, and background-image cannot supply its background. See CSS Pseudo-Elements · Styling Highlights for the applicable properties.

Choose the foreground and background as a pair. The WCAG · Contrast (Minimum) ratio of 4.5:1 for ordinary text is a reference for picking readable colors. If the rule has no visible effect, confirm the selector matches the element and check for a more specific rule. High-contrast settings in the browser or operating system may use system colors instead.