Controlling HTML text selection with CSS
Some days ago I found myself googling "One click text selection in HTML"; I was looking for some simple javascript that'd let me select the whole html text block with a one click.
To my surprise, I found out that this can be quite easily done with CSS using a property called user-select
.
CSS user-select
lets you control the way text selection works in your html pages, things like one-click text selection or disabling text selection are some examples of this.
Let's Dive in
MDN docs on user-select
user-select: auto; /* let the browser decide */
user-select: text; /* select only text */
user-select: none; /* don't select anything */
user-select: all; /* select everything */
user-select: contain; /* selection contained within element bounds */
Let's go through these:
user-select: auto;
Setting the value to 'auto' will let the browser decide how the text selection would work. Which, in most cases means that the text selection would work in the usual, natural way.
user-select: none;
Disables the text selection altogether. User would not be able to highlight and select text if the block has user-select: none
rule applied to it.
user-select: text;
The text can be selected by the user, this is the natural text selection behaviour. The value 'text' is different than 'auto' in the sense that it resets the behaviour to the normal text-selection behaviour rather then letting the browser decide what to do.
user-select: all;
Let's you select the whole text block with a single click. The text would get highlighted on click which.
Here's a small codepen demonstrating the use of these properties:
Hope you enjoyed this, let me know your thoughts in the comments. 🙂