DEV Community

Cover image for CSS user-select
Daniel Schwarz
Daniel Schwarz

Posted on • Updated on

CSS user-select

user-select defines if (and to what extent) users can select content within an element — the following code samples the various valid values and explains the limitations that those values impose. user-select has nothing to do with ‘styling.’

user-select: text; // text can be selected

user-select: none; // text can't be selected

user-select: contain; // within the element

user-select: all; // all or nothing

user-select: auto; // depends, see below

<element>:before, <element>:after {
    user-select: auto; // user-select: none;
}

<editable element> {
    user-select: auto; // user-select: contain;
}

<any other element> {
    user-select: auto;
    // <child> inherits ‘all’ or ‘none’
    // if no inheritance, then user-select: text;
}
Enter fullscreen mode Exit fullscreen mode

Prefixing user-select

Prefixing is needed for maximum web browser support (source: caniuse.com).

-ms-user-select: <value>; // internet explorer
-moz-user-select: <value>; // firefox for android 
-webkit-user-select: <value>; // opera, edge, safari
Enter fullscreen mode Exit fullscreen mode

Using user-select

Before we wrap up, let’s explore a user-select use-case where we ‘lock’ an article.

HTML

<article id="article">Lorem ipsum solor sit amet…</article>
Enter fullscreen mode Exit fullscreen mode

JavaScript

if(articleShouldBeLocked) {

    const article = document.querySelector("#article");

    article.classList.add("locked"); // used for styling

    article.querySelectorAll("a").forEach(a => a.setAttribute("tabindex", "-1")); // skip focusing

    document.body.setAttribute("oncontextmenu", "return false;"); // block the right-click contextmenu

}
Enter fullscreen mode Exit fullscreen mode

CSS

#article.locked {
    opacity: 0.5; // styling
    filter: blur(0.5rem); // styling
    user-select: none; // block selections
    pointer-events: none; // block link clicks
}
Enter fullscreen mode Exit fullscreen mode

Did I miss something?

Well if I did…then drop a comment already!

Buy Me A Coffee 😘

Discussion (2)

Collapse
joelpatrizio profile image
Joel Patrizio

I didn't know about this property, and it seems quite useful. Thanks for the guide!
Short and straight to the point ;)

Collapse
mrdanielschwarz profile image
Daniel Schwarz Author

Happy to help!

One line of CSS is better than several lines of JavaScript :)