CSS::selection | Style Selected Text

The CSS ::selection pseudo-element is used when we need to change the default style of a selected portion of text on a web page. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      ::selection {background-color: burlywood; color: white;}
   </style>
</head>
<body>

   <p>This is para one.</p>
   <p>This is para two.</p>
   <p>The three famous and most used web developing languages are, HTML, CSS, and JavaScript.</p>

</body>
</html>

This is para one.

This is para two.

The three famous and most used web developing languages are, HTML, CSS, and JavaScript.

Note: If you select some text from the above three paragraphs, then the defined style will get applied to the selected portion.

In the above example, the following CSS code:

::selection {background-color: burlywood; color: white;}

targets the user-selected text in the document. The ::selection pseudo-element is used to apply styles to the portion of a document that is highlighted by the user with their mouse or keyboard.

Therefore, when the user selects text on the web page, the background color will change to a light brown (burlywood) and the text color will change to white.

In the above example, there are three "p" elements with text in the given HTML code. If a user selects any text within these paragraphs, the selected text will be styled with the CSS ::selection properties.

CSS ::selection syntax

The syntax of the ::selection pseudo-element in CSS is as follows:

::selection {
   // CSS properties go here
}

The CSS properties contained within the curly braces determine the style of the selected text.

List of properties that can be applied to CSS ::selection

Because the selection is a limited portion of the page, not all CSS properties can be applied to the ::selection pseudo-element, and some properties do not make sense in this context. The following are some CSS properties that can be used with the ::selection pseudo-element.

Advantages of the "::selection" pseudo-element in CSS

Disadvantages of the "::selection" pseudo-element in CSS

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this article? Share it!



Like/follow us on social media for updates!