How to disable text selection highlighting?

Ask a question
5

For anchors that act like buttons (for example, Questions, Tags, Users, etc. at the top of the Stack Overflow page) or tabs, is there a CSS standard way to disable the highlighting effect if the user accidentally selects the text?

I realize this could be done with JavaScript, and a little googling yielded the Mozilla-only -moz-user-select option.

Is there a standard-compliant way to accomplish this with CSS, and if not, what is the “best practice” approach?

Coin iconoffer bounty
add comment

1 Answer

1

There is not enough standard compliant way to acoomplish it, but all modern browser except Internet Explorer 9 and earlier have support for user-select (but still need vendor prefix). All css variation are:

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

To use this you can add noselect class to element. Example:

<p class="noselect">This text should be cannot selected</p>

Also there a Javascipt Solution that work. The solution is just returning false when onselectstart event is called. Example:

<p onselectstart="return false;">This text should be cannot selected</p>

You can combine those solution into this code:

<style>
.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
}
</style>
<p class="noselect" onselectstart="return false;">This text should be cannot selected</p>

just a comment, PostCSS automatically fills browser support part. in case if the reader does not about it

Arthur Dilanyan
add comment

Your Answer