How to Disable Text Selection in HTML with CSS?
Last Updated :
29 Jul, 2024
Disabling text selection in HTML can be useful in scenarios where you want to prevent users from copying text, dragging elements, or accidentally selecting text while interacting with web page elements.
These are the following approaches:
Using user-select Property
In this approach we will use the user-select CSS property. This property is used to control the user’s ability to select text. This is the most straightforward and modern way to disable text selection.
Syntax:
element {
user-select: none;
}Example: In below example we are using user-select to disable text selection in HTML with CSS.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<style>
p {
user-select: none;
}
</style>
<title>Disable Text Selection</title>
</head>
<body>
<h3>Disable text selection using user-select property</h3>
<p>This text cannot be selected.</p>
</body>
</html>
Output:
OutputUsing Vendor Prefixes for Cross-Browser Compatibility
To ensure compatibility across different browsers, it is important to include vendor prefixes for the user-select property. Different browsers might require specific prefixes to support the user-select property. This approach ensures that the text selection behavior is consistent across all major browsers.
Syntax:
element {
-webkit-user-select: none; /* Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Standard Syntax */
}Example: To disable text selection on a div element with cross-browser support:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<style>
div {
-webkit-user-select: none;
/* Safari */
-moz-user-select: none;
/* Firefox */
-ms-user-select: none;
/* Internet Explorer/Edge */
user-select: none;
/* Standard Syntax */
}
</style>
<title>Disable Text Selection</title>
</head>
<body>
<p>This text can not be selected.</p>
<div>This text cannot be selected in any browser.</div>
</body>
</html>
Output:
Output
Explore
HTML Basics
Structure & Elements
Lists
Visuals & Media
Layouts & Designs
Projects & Advanced Topics
Tutorial References