HTML & CSS

How to Disable Text Selection with CSS

How to Disable Text Selection with CSS

In web development, there are times when you might want to prevent users from selecting text on your webpage. This can be useful in cases where you want to protect the content from being copied or to enhance the user experience by preventing accidental text selection during interactions. Fortunately, CSS provides a simple way to disable text selection.

Using the user-select Property

The user-select property is a CSS property that controls the user’s ability to select text. By setting this property to none, you can prevent text selection. Different browsers have their own prefixes, so it’s important to include these to ensure compatibility across various browsers.

Here’s the CSS code to disable text selection:

.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none; /* Safari */
  -khtml-user-select: none; /* Konqueror HTML */
  -moz-user-select: none; /* Old versions of Firefox */
  -ms-user-select: none; /* Internet Explorer/Edge */
  user-select: none; /* Non-prefixed version, currently
                       supported by Chrome, Edge, Opera and Firefox */
}

Explanation

  • -webkit-touch-callout: none;: This disables the callout (context menu) on iOS Safari when the user performs a long press.
  • -webkit-user-select: none;: This is for Safari.
  • -khtml-user-select: none;: This is for older versions of Konqueror, a web browser for KDE.
  • -moz-user-select: none;: This is for older versions of Firefox.
  • -ms-user-select: none;: This is for Internet Explorer and Edge.
  • user-select: none;: This is the standard, non-prefixed property for modern browsers like Chrome, Edge, Opera, and the latest versions of Firefox.

How to Apply

To apply this CSS rule, you simply need to add the noselect class to any HTML element you want to protect from text selection. For example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .noselect {
      -webkit-touch-callout: none;
      -webkit-user-select: none;
      -khtml-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
    }
  </style>
  <title>Disable Text Selection</title>
</head>
<body>
  <div class="noselect">
    This text cannot be selected.
  </div>
</body>
</html>

With this approach, you can easily control text selection on your web pages, enhancing user experience and protecting your content as needed

Suggested Articles

Leave a Reply

Your email address will not be published. Required fields are marked *