Home  »  GuidesHow ToProgrammingTechnology   »   How to Disable Text Selection Highlighting Using CSS

How to Disable Text Selection Highlighting Using CSS

You can use CSS for many things and one of the uses is to disable text selection in your text, tabs, buttons, and more.

This can be done using the user-select selector which is supported in all major web browsers except for Internet Explorer 9 and earlier versions. We will highlight a JavaScript solution that can be used for older web browsers.

The user-select syntax and available variations:

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

Usage in HTML:

<p>
   Selectable text.
</p>
<p class="dontselect">
   Non-selectable text.
</p>

The following JavaScript solution can be used in Internet Explorer 9 and older browser versions to disable text selection highlighting:

onSelectStart="return false;"

Usage in HTML:

<p>
  Selectable text.
</p>
<p onselectstart="return false;">
  Non-selectable text.
</p>

Bonus Tip to Disable Text Selection Highlighting

You may also want to prevent the context menu from appearing on elements like buttons that have their selection prevented. To do that, add this code to the entire page, or just those button elements:

$("body").on("contextmenu",function(e){
    return false;
});

or:

$("#buttonId").on("contextmenu",function(e){
    return false;
});

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.

Available under:
Guides, How To, Programming, Technology

Tagged with:
, , , ,