Prevent Users from Copying the Content of a Web Page with Pure CSS

When building my own personal blog, on the details page of the blog, I want to have different ways of copying different content. For example, for code blocks, I want readers to click to copy, which is convenient for readers to debug locally. As for the text description, it is hoped that readers will not be allowed to copy it.

As a determined extremist who can use CSS and never JS, I finally found user-select in CSS3. user-select can be used to control whether the user can select text on a web page, all or part of it.

How Do Pure CSS Prevent Users from Copying the Content of a Web Page

We will introduce how to control the content of the page copied by the user, including Select All, Select None, and Partially Selected.

1. Select All

In many cases, users may want to copy the complete content at one time, such as a piece of code, password, and some keys. user-select:all allows the user to click to select elements. Here we demonstrate the effect under three different HTML tags.

h2 {
user-select: all;

code {
user-select: all;
width: 500px;
display: block;
padding: 10px;
color: #31808c;
background-color: #f5f4ef;

div {
user-select: all;
<h2>Click to Try It Out</h2>
const num = 1;

const result = (function () {
delete num;
return num;

const num = 1; const result = (function () { delete num; return num; })();

But all also have an embarrassing shortcoming. As long as you set all, then you can not select part of the content. So, how do you allow users to copy the content of a web page? Please see the next part.

2. Select None

For elements in web pages, you can use user-select: none; to prevent the user from selecting content.

3. Partially Selected

Why is there such a statement? For normal web pages, we can select specific content. Therefore, here mainly refers to the elements that cannot be selected on the opposite side. For example, there is such a tag sup in HTML, which is mainly used to add corner labels to elements.

<p>I have a superscript behind me<sup>1</sup>I have a superscript in front of me</p>

When you want to copy this text, there is a corner mark after me 1 and there is a corner mark in front of me, then this corner mark will also be copied. At this point, we need to set the corner mark. This setting also ensures that when your p tag is user-select:all, the copy will also ignore the corner tag!

sup {
-webkit-user-select: none;
user-select: none;

4. How to Set the Selected Style

CSS provides the ::selection pseudo-element to style text selections. You can style text selections by targeting the ::selection pseudo-element. However, only the following properties can be set.

outline and its longhands
text-decoration and its associated properties
text-emphasis-color (en-US)

Examples are as follows.

p::selection {
color: #fffaa5;
background-color: #f38630;
text-shadow: 2px 2px #31808c;

Leave a reply