How to Prevent Selection on Specific Elements with CSS

If you’ve ever found yourself wondering if there’s a CSS-only way to turn off or disable user-selections on a web page, you’re totally in luck, because we’re going to talk about that right now.

CSS’s user-select property can be used to disable select on an entire page or just on specific elements you’d like to target. It’s really cool because being able to apply it to only certain elements gives you a lot more freedom than having to disable selection for the entire page if you only really need to disable it for one line of text, or perhaps for a particular set of elements.

Join us in our newest publication:

It’s important to note that the user-select property is sadly not supported universally on all browsers, so when implementing it, you’ll have to remember to use your vendor prefixes, or it might not work.

Here’s an example of how you’d use the property to disable user selection on an entire page.

body, html{
     -webkit-user-select: none;
     -moz-user-select: none;
     -ms-user-select: none;
     user-select: none;
}

If you wanted to use the property to disable user selection on just a single element, you can probably guess how that would go down, but we’ll show you anyway. For the purposes of this example, let’s say you want to disable selection for all <p> elements. That would look like this:

 

p{
     -webkit-user-select: none;
     -moz-user-select: none;
     -ms-user-select: none;
     user-select: none;
}

Pretty simple, right? Other values that this property takes are auto, which is the property’s default value allows user-selection to occur as long as it’s allowed by the browser. The other two values that the property takes are text, which allows the user to select text only, and all, which allows for text selection to happen with a single click rather than a double click. In this case, all a user needs to do to select a chunk of text would be to click it once, so this value actually makes the selection process a lot easier.

Share and Enjoy !

0Shares
0 0