Customizing Text Selection with the ::selection Pseudo-Element in CSS


::selection Pseudo-elements

The ::selection pseudo-element in CSS allows you to style the portion of text that a user selects or highlights within an HTML document. This feature gives you the ability to customize the appearance of selected text, such as changing the background color, text color, or other properties, to provide a unique and visually appealing experience on your website.

Source Code :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>selection Pseudo-elements</title>
    <style>
      p::selection {
        color: yellowgreen;
        background: #111;
      }
    </style>
  </head>
  <body>
    <h3>::selection Pseudo-elements</h3>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Obcaecati qui optio alias eos aspernatur, soluta earum et, in aperiam laudantium voluptatum perspiciatis numquam fugit quas eum accusantium molestias voluptate dolorem!</p>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Obcaecati qui optio alias eos aspernatur, soluta earum et, in aperiam laudantium voluptatum perspiciatis numquam fugit quas eum accusantium molestias voluptate dolorem!</p>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Obcaecati qui optio alias eos aspernatur, soluta earum et, in aperiam laudantium voluptatum perspiciatis numquam fugit quas eum accusantium molestias voluptate dolorem!</p>
  </body>
</html>

Live Preview

The CSS code you provided attempts to apply styles to the selected or highlighted text within a <p> (paragraph) element. However, there is a minor error in the selector. It should be ::selection, not ::selection.

Using the ::selection pseudo-element allows you to enhance the user experience on your website by providing a visually appealing and consistent style for selected text. However, always remember to test your styles across different browsers to ensure compatibility.

p::selection: This selector targets the ::selection pseudo-element within <p> elements. It specifies that the styles inside the block should be applied to the text selected within <p> elements.

color: yellowgreen;: This property sets the color of the selected text to "yellowgreen." When a user highlights text within a <p> element, the selected text will appear in the "yellowgreen" color.

background: #111;: This property sets the background color behind the selected text to a dark gray color (#111). When text is selected within a <p> element, the background behind the selected text will be dark gray.


CSS Tutorial


Properties Reference


Cascading Style Sheet


Flexbox Tutorial


CSS Grid Tutorial


Transitions Properties


CSS Properties with Examples


CSS Selectors


CSS Pseudo Elements


CSS Attribute Selectors


Input Pseudo Classes


CSS Examples


CSS Animation Projects