How to disable text selection using CSS

By

Learn how to disable text selection in CSS with the user-select: none rule and its browser prefixes, then re-enable it on elements with user-select: text.

~~~

To disable text selection in CSS, apply user-select: none; to the element. Users can no longer highlight that text with the mouse or select it with cmd-A / ctrl-A.

By default browsers let us select the text in the page using the keyboard, pressing the cmd-A combination on a Mac for example, or using the mouse.

That’s the right behavior for a document. But if you’re building something that feels like an app, selection gets in the way. Double-clicking a button and seeing its label highlight in blue looks broken.

Use the user-select: none; CSS rule.

For a long time you needed browser prefixes, as https://caniuse.com/#feat=user-select-none tells us:

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

Today the situation is better. Every modern browser supports the unprefixed user-select, and -webkit-user-select covers older Safari versions. The -khtml- and -ms- lines only matter if you support very old browsers.

The -webkit-touch-callout: none; line does something related but different: on iOS Safari it disables the callout that pops up when you long-press an element.

Where should you apply it?

One thing I use sometimes is to make all the app interface unselectable applying user-select: none; on the body element, then I can re-enable it on specific elements, using:

user-select: text;

This works because the effect of user-select: none propagates down to all the children, so a single rule on body covers the whole page.

A more targeted approach is to disable selection only on interface parts, like buttons, tabs and labels:

.toolbar {
  user-select: none;
}

What this rule is not

user-select: none changes the selection behavior. It’s not a security or copy-protection feature.

The text is still in the DOM. Anyone can read it in the page source or copy it from the browser dev tools. Don’t use it to “protect” content.

One pitfall

Be careful not to disable selection on actual content. If a user tries to copy an error message, a code snippet or a product code and nothing highlights, that’s frustrating.

If you went with the body approach and users report they can’t copy something they legitimately need, the fix is one rule:

.error-message {
  user-select: text;
}

Keep the app chrome unselectable, and keep the content selectable.

Tagged: CSS · All topics
~~~

Related posts about css: