CSS prevents users from selecting web page text
CSS prevents users from selecting webpage text
In web design, sometimes we want users to be unable to select text on a webpage to avoid unnecessary copying or screenshots. CSS provides a simple way to prevent users from selecting text on a web page. Below, we’ll explain how to do this.
Using the CSS user-select Property
There’s a CSS property called user-select
that controls whether users can select text. This attribute has the following possible values:
auto
: The browser automatically determines whether text can be selected.none
: Text cannot be selected.text
: Text can be selected.
We can set this property to prevent users from selecting text.
Example of Preventing Users from Selecting Text
Below, we’ll use a simple example to demonstrate how to use CSS to prevent users from selecting text:
<!DOCTYPE html>
<html Tutorial">html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Disable User Selection of Web Page Text</title>
<style>
.non-selectable {
user-select: none;
}
</style>
</head>
<body>
<div class="non-selectable">
This is text content that prevents user selection.
</div>
</body>
</html>
In the example above, we create a div
element, give it a class named non-selectable
, and set user-select: none;
to prevent users from selecting text. You can copy the code into an HTML file and open it in a browser to see the effect.
Further Control over Selectivity
Beyond simply disabling text selection globally, we can also precisely control which elements can and cannot be selected. For example, we can allow users to select text in one element, but disallow it in another.
Here is a slightly more complex example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Disable User Selection of Web Page Text</title>
<style>
.selectable {
user-select: text;
}
.non-selectable {
user-select: none;
}
</style>
</head>
<body>
<div class="selectable">
This is text content that allows the user to select.
</div>
<div class="non-selectable">
This is text content that prohibits the user from selecting.
</div>
</body>
</html>
In the example above, we create two div
elements, one that allows user selection and one that doesn’t. You can view the result to see how to precisely control text selectability.
Summary
Using the CSS user-select
property, we can easily control whether users can select text on a web page. This can be very useful for certain design requirements, but it’s important to note that this approach doesn’t completely prevent users from copying text, as they can still access the content through other means. Therefore, it’s important to balance design needs with feasibility.