How to Disable Text Selection Highlighting in CSS
Ever click a button or tab and have all the text instead? You can prevent simple accidents like that from happening again with vanilla CSS - no JavaScript needed!
Not only can accidental text selection affect buttons and tabs, but it can also affect carousels and sliders, and especially when using the <canvas>
* tag.
*Sometimes you'll make a drag-n-drop game of some sort and accidentally select everything instead 🥴.
CSS Solution: user-select Property
.select-none {
user-select: none; /* user cannot select text */
}
.select-auto {
user-select: auto; /* makes it work like an inherited property - more on this below */
}
.select-text {
user-select: text; /* text in the element can be selected */
}
.select-all {
user-select: all; /* automatically select all the text in an element when clicked */
}
The user-select
property isn’t 'naturally' an inherited property, but setting it to the value auto
makes it behave like one.
According to CanIUse, it has 96% of coverage! The only vendor prefix that’s "needed" now is -webkit-
for iOS, MacOs, and older Android browsers. Even IE 10/11 have support (with a -ms-
prefix).
Here are all the prefixes, for the curious:
.prefixes {
-webkit-user-select: none; /* only prefix I would use, personally */
-moz-user-select: none;
-ms-user-select: none;
user-select: none; /* covers all use-cases except Apple and IE */
}
Examples, you say?
You cannot select this text.
Click to select all this text.
You can select all but the emojis 🙃 in this text - helpful for letting users copy/paste 💻 only important content on your webpage 🤌.
I personally haven’t used this property too much - but I can see the use-cases for it! Sometimes, I’ll see it being used in the wild to block/protect content, but that can quite easily be bypassed and, in my opinion, makes a user-unfriendly experience.
But, using it to block out emojis and whatnot, or even the reverse: a one-click select all for easy copy/paste, can help enhance user experience.