Disabling text selection can be useful in certain situations, such as when you want to prevent users from copying and pasting sensitive information or when you want to improve the user experience by preventing accidental selections. In this tutorial, we will explore how to disable text selection using CSS.
The user-select
property is used to control whether an element’s text can be selected. This property has several values, including none
, text
, toggle
, element
, elements
, all
, and inherit
. The none
value disables text selection entirely, while the other values enable it in different ways.
To disable text selection on an element, you can use the following CSS code:
.noselect {
-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 */
}
You can then apply this class to the elements you want to disable text selection on:
<p>
Selectable text.
</p>
<p class="noselect">
Unselectable text.
</p>
Note that the user-select
property is not supported in all browsers, and some browsers may require vendor prefixes (such as -webkit-
or -moz-
) to work correctly. However, according to Can I Use, the user-select
property is currently supported by most major browsers.
It’s also worth noting that disabling text selection can have accessibility implications, as it can make it difficult for users with disabilities to interact with your content. Therefore, you should use this property judiciously and only when necessary.
In addition to disabling text selection on specific elements, you can also disable it on the entire page by applying the noselect
class to the body
element:
body {
-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 */
}
This can be useful if you want to prevent users from copying and pasting any content on your page.
In conclusion, disabling text selection with CSS is a simple process that involves using the user-select
property. By applying this property to specific elements or the entire page, you can control whether an element’s text can be selected. However, you should use this property judiciously and only when necessary, as it can have accessibility implications.