CSS provides a powerful way to control the visual aspects of a webpage, and one common requirement is the ability to turn off or disable text selection highlighting.
Whether you want to enhance the design or prevent users from copying content, CSS offers a solution. In this article, we will look at how to achieve this.
To disable text selection in CSS, use the user-select
property. By setting it to ’none’ for specific elements, you can make them unselectable.
Let’s take a look at the basic code snippet:
.no-select {
user-select: none;
}
To ensure your CSS code works seamlessly across different browsers, it’s essential to include vendor prefixes.
This is particularly important for older versions of browsers.
Here’s an example with prefixes for Safari, Chrome, Firefox, and Internet Explorer.
.no-select {
-webkit-user-select: none; /* for Safari and Chrome */
-moz-user-select: none; /* for Firefox */
-ms-user-select: none; /* for Internet Explorer 10+ */
user-select: none; /* for modern browsers */
}
Now that we have CSS code ready, you can apply the no-select
class to the elements you want to make unselectable.
In the following HTML example, the <p>
element with the “no-select” class will be unselectable, while the <p>
element without the “no-select” class can be selectable.
<p class="no-select">This text cannot be selected.</p>
<p>This text can be selected.</p>
💡 Extra Tips on Text Selection for you:
On the other way round, if you want a whole line of text to be selected at once when a user clicks on the block of text once
(i.e., to select the entire element and its contents on a single click), you can use the CSS style below.
The user-select
property is set to ‘all’.
.select-all {
user-select: all;
}
<p class="select-all">This text can be selected just with a single click.</p>
There you have it on how to turn off or disable text selection highlight in CSS.