In many web applications, you may want to prevent users from selecting text. Whether you’re building a custom UI component like buttons, headers, or image captions—or simply want to avoid accidental text selection—CSS provides a clean and efficient way to do this.
In this post, you’ll learn how to disable text selection using CSS, with full browser support and practical examples.
❓ Why Disable Text Selection?
Disabling text selection can improve user experience by:
- Preventing accidental highlighting of buttons, labels, or UI elements.
- Avoiding content copying in sensitive interfaces.
- Improving aesthetics in interactive components (like drag-and-drop elements).
⚠️ Note: This should not be used to try to protect text from being copied. If text is visible on the screen, it can always be copied via developer tools.
✅ CSS Solution: user-select
Property
The CSS user-select
property controls whether users can select text within an element.
📌 Basic Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Disable Text Selection</title>
<style>
.no-select {
user-select: none;
-webkit-user-select: none; /* For Safari */
-moz-user-select: none; /* For Firefox */
-ms-user-select: none; /* For Internet Explorer */
}
</style>
</head>
<body>
<p class="no-select">
You can't select this text by dragging your mouse over it.
</p>
</body>
</html>
🎯 Explanation of Code
user-select: none;
– Disables text selection in modern browsers.- Vendor prefixes like
-webkit-
,-moz-
, and-ms-
are added for compatibility with Safari, Firefox, and older versions of Internet Explorer.
🧠 When to Use
You might want to disable text selection for:
- Navigation bars
- Buttons
- Image captions
- Custom widgets or cards
- Drag-and-drop elements
Example:
button, nav, .card-header {
user-select: none;
}
🚀 Bonus: Enable Text Selection Only on Specific Areas
You can selectively disable text selection on the container while allowing it inside child elements:
<div class="no-select">
This text can't be selected.
<p style="user-select: text;">
But this paragraph can be selected.
</p>
</div>
🧾 Conclusion
Disabling text selection with CSS is quick, efficient, and fully supported across modern browsers. Just use user-select: none;
and include vendor prefixes for maximum compatibility. It’s a great way to improve usability and polish your interface design—just remember not to rely on it for content protection.