On a web page, we typically should not disable text selection, but there are a few cases where having it enabled can take away from the user experience. Normally, we do not want to take away a user's ability to select text, as that will lead to a bad user experience. There was a time when a small number of websites would stop users copying article text as a method of stopping plagiarism, but thankfully that is far less common today.
Having said that, there are a notable number of examples where disabling text selection can actually improve user experience. For example:
- On HTML elements that trigger events, especially on mobile - where tapping or double tapping might lead to text selection
- On drag and drop interfaces, where a user has to drag an element - we don't want that drag to trigger text selection too.
- On many other custom web-built user applications where text selection needs to be limited to certain elements or situations. For example, on a text editor, we usually don't want the button that makes text bold to be selectable, since it is a button.
Fortunately there is an easy way in CSS to disable text selection on certain elements if you need to.
How to disable text selection in CSS
All modern browsers (with the exception of some versions of Safari) support the user-select
property, which makes any HTML element unselectable. For example, if you wanted all buttons not be selectable, you could write the following:
button {
-webkit-user-select: none;
user-select: none;
}
We have to use -webkit-user-select
since Safari still requires it. If you want to support Internet Explorer (which is becoming less and less common), you can also use -ms-user-select
:
button {
-ms-user-select: none;
-webkit-user-select: none;
user-select: none;
}
This single property will stop user selection. user-select
also has other properties, in theory, but the support for these vary.
-
user-select: none
- no user select on the element. -
user-select: text
- you can only select the text within the element -
user-select: all
- tapping once will select the entire elements content. -
user-select: auto
- the default, lets you select everything like normal.
The support for each of these varies, but you can find a full, up to date list of support for user-select on caniuse.
To see some demos on this, check out the original article here.