Disabling Text Selection Highlighting with CSS

Hero image for Disabling Text Selection Highlighting with CSS.
Hero image for 'Disabling Text Selection Highlighting with CSS.'

What was once a difficult problem for frontend developers to resolve, stopping users from being able to select text where they should not be able to (for example: inside of actionable elements such as buttons).

Now, with the widespread browser support, it is as simple as using userselect: none.

.classname {  user-select: none;}

This pseudoelement will simply tell the browser that the area matched by the selector should not be selectable. If you aren't using an autoprefixer and want the best crossbrowser support (Internet Explorer 10 and above, Opera 15+, etc) then you will still need to use a number of prefixes to capture all possible variants:

.classname {  -moz-user-select: none;  -khtml-user-select: none;  -webkit-user-select: none;  user-select: none;}

The only two gotchas to bear in mind here are:

  • On iOS, if you set an input element to userselect: none (or webkituserselect: none) then the input will essentially become disabled: it will not be focusable, and thus text cannot be input by the user at all.
  • Some manufacturers' versions of Android 4.0 (Ice Cream Sandwich) and below have been known not to work, although most do. These are devices released towards the end of 2011 so it is unlikely to be something you come across in any real user numbers.

The Old‑Fashioned Way

If the inability to select text is an absolute requirement for your project, and you still need to support Internet Explorer 9, or the very specific versions of Firefox that don't support the various browserprefixed permeations of userselect, then there is a sortof workaround that will get you part of the way there by using the ::selection pseudoelement:

.classname::selection {  background: transparent;}// If not using an autoprefixer and want to support Firefox// versions 2 - 61, you also need to use the 'moz' prefix:.classname::-moz-selection {  background: transparent;}

Whilst this won't stop users from being able to highlight text on your website, what it will do is visually hide the fact that the text is being selected by setting the default browserblue to transparent instead.

In this case, do bear in mind that these two cannot be combined into a single ruleset because if the browser comes across what it considers an invalid selector whilst parsing the ruleset, it will discard the entire thing.

For a complete solution combining the two approaches (but not using an autoprefixer), your Sass might look a little like this:

.classname {  -moz-user-select: none;  -khtml-user-select: none;  -webkit-user-select: none;  user-select: none;  &::selection {    background: transparent;  }  &::-moz-selection {    background: transparent;  }}

Fin.


Categories:

  1. Accessibility
  2. Cross‑Browser Compatibility
  3. CSS
  4. Development
  5. Front‑End Development
  6. Sass
  7. Typography