How to disable text selection using CSS?

Browsers, by default, let us select the text on a webpage using the mouse as well as the keyboard(Ctrl+A on windows). But, you might sometimes need to prevent this default text selection for a particular element or the whole webpage itself.

With CSS we can very easily achieve this. All you need to do is apply user-select: none; on the element that you want to disable text selection.

The following example disables the text selection on a div element:

Example:

div{
   user-select: none;
}

The above fix might not work perfectly in all the browsers. If you want to prevent user selection for all the browsers, you have to use browser prefixes.

This is how you can do this:

Example:

div{
    -webkit-touch-callout: none;
      -webkit-user-select: none;
       -khtml-user-select: none;
         -moz-user-select: none;
          -ms-user-select: none;
              user-select: none;
}

Disable text selection for the whole page

If you want to disable the text selection for the whole page, you can do this by applying user-select: none; on the body element.

Here is a working example of it:

Example:

body{
   user-select: none;
}

You can read more about the user-select property here-> CSS user-select property

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts