Disable Text Selection and Highlighting with CSS

There are situations when designing a website where text selection is not desirable. This may not apply to the entire web page but only to certain elements on it. Disabling the ability to select and highlight text can be achieved through a number of different means. Using JavaScript is one method but sometimes the preference may be to utilize CSS instead.

CSS Option 1

The following CSS code covers disabling text selection on all major browsers: The following code will be used to place text within the area that can be selected and highlight, as well as the area where the text cannot be selected and highlighted. Almost all browsers are supported by user-select, except for Internet Explorer 9 and earlier. However, as this is not a standard feature, there could be problems in implementing the code in different browsers.

CSS Option 2

An alternative CSS approach using a div container would use the following code: Place the text that must not be selectable and highlighted within the following div tags: Since this property is not inheritable, the tag will have to be applied for every element within the div container.

The Javascript Option

The JavaScript option needs to be considered when the CSS options above do not work. The following code can be used for an element’s descendents. A simpler JavaScript option that can be considered is: It is important to remember that none of these options cover all possibilities. Furthermore the selection ability is only disabled within the elements covered with either the CSS or JavaScript code. Other elements before and after the target text can still be highlighted. This approach is not ideal for disabling text selection and highlighting of an entire page. Remember there is no quick and easy way to achieve this feature, particularly with CSS, so Javascript may be the most viable option.

When would you do this?

Many webmasters opt for disabling the text selection and highlighting feature to prevent unauthorized copying of content from their website. However, there is no foolproof way to disable the text selection entirely. Disabling text selection may work for the amateur content scrapers but does not prevent copying the HTML and automated copy scraping programs. Therefore it is of limited benefit for the intended purpose.

Leave a Comment