CSS prohibits selected text
Disable CSS Text Selection
In web development, sometimes we need to prevent users from selecting text on a web page. This can prevent users from copying content and protect our original work. CSS provides a simple way to prevent text from being selected. This article will detail how to use CSS to achieve this effect.
How to Prevent Text from Being Selected
To prevent users from selecting text, we can use the user-select
property in CSS. The user-select
attribute controls whether users can select text. It has the following values:
auto
: The browser’s default behavior, allowing users to select text.none
: Allows users to select text.text
: Allows users to select text.
We can prevent users from selecting text by setting the user-select
property to none
. The specific CSS code is as follows:
.disable-select {
-webkit-user-select: none; /* Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE/Edge */
user-select: none; /* Standard syntax */
}
In the code above, we define a .disable-select
class and set the -webkit-user-select
, -moz-user-select
, -ms-user-select
, and user-select
attributes to none
to prevent users from selecting text. Please note that different browsers require different prefixes to ensure compatibility.
How to Disable Text Selection
To disable text selection, simply add the .disable-select
class to the element you want to disable. For example, if we want to disable text selection within a <div>
element, we can write the following:
<div class="disable-select">
This text cannot be selected. </div>
With the above code, the text within the <div>
element will not be selectable by the user. Of course, you can also apply the .disable-select
class to other elements where you want to disable text selection.
Example
Let’s take a look at an example that demonstrates how to disable text selection using CSS. First, let’s create an HTML file with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Disable Text Selection</title>
<style>
.disable-select {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
</style>
</head>
<body>
<div class="disable-select">
This text cannot be selected.
</div>
</body>
</html>
In the above code, we define the .disable-select
class within the <style>
tags and apply it to a <div>
element, making the text within that element unselectable. Save the file and open it in a browser; you’ll find that the text cannot be selected.
Summary
Through this article, we learned how to use CSS to prevent users from selecting text. This technique can effectively protect web content and prevent it from being misused by criminals. In actual development, if you need to prevent users from selecting text, you can use user-select: none;
to achieve this.