Thursday, 27 December 2012

How to disable text selection with CSS



Use the following CSS rule to prevent text selection:

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

or use inline rule like this:

<div style='-moz-user-select: none;-webkit-user-select: none;' onselectstart='return false;'>unselectable text</div>

this works in Safari, Firefox and Internet Explorer and Chrome.

here a simple example:

*.unselectabletxt {
   -moz-user-select: -moz-none;
   -khtml-user-select: none;
   -webkit-user-select: none;

   /*
     Introduced in IE 10.
     See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
   */
   -ms-user-select: none;
   user-select: none;
}

For IE < 10 and Opera, you will need to use the unselectable attribute of the element you wish to be unselectable. You can set this using an attribute in HTML:

<div id="foo" unselectable="on" class="unselectabletxt">...</div>

If you want to disable text selection on everything except on <p> elements you can do this in css (watch out for the -moz-none which allows override in sub-elements, which is allowed in other browsers with none):

* {
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: -moz-none;
-o-user-select: none;
user-select: none;
}

p {
-webkit-user-select: text;
-khtml-user-select: text;
-moz-user-select: text;
-o-user-select: text;
user-select: text;
}


Share:

No comments:

Post a Comment