How to disable text selection highlighting using CSS


In this article, we will learn how to disable text selection on a webpage.

In a webpage, when we double-click or drag our cursor over some text, it will be selected or highlighted with a default blue color.

And if you want to prevent this behavior on your website or a single webpage, we can use the

  1. user-select CSS property, or
  2. ::selection pseudo-element.

Let's see each property with example.

Using user-select to disable text selection highlighting.

The user-select property defines whether a user can select the text of an HTML element.

Syntax:

user-select: auto|none|text|all;

Suppose we have two div, with id 'highlight' and other with 'no-highlight'.

And we have set the user-select property to none in the no-highlight div. Now user cannot select/highlight text from the div.

Example:

.no-highlight{
  user-select: none;
}

Edit determined-goldwasser-wq36vb

Disable text selection highlighting using ::selection

The ::selection pseudo-element in CSS allows us to add styles to the portion of text that has been highlighted by a user.

We can use the ::selection pseudo-element to remove the default highlighting of text selection.

We can apply style properties like background-color, color, cursor, and outline.

Syntax

::selection {
  css declarations;
}

To remove the default selection highlighting color we have to set color and background CSS properties to none.

::selection {
    color: none;
    background: none;
}
/* For Mozilla Firefox */
::-moz-selection {
    color: none;
    background: none;
}

💾 Recommended Articles