Using CSS to Control Text Selection

Will Boyd digs into the user-select CSS property:

CSS lets you control how text selection behaves and appears on your pages. This can help you improve usability in certain situations and add a little bit of visual flair. Let’s dive in!

His posts includes a very nice hack to make user-select: all; work only at first click.

code {
  -webkit-user-select: all;
  user-select: all;
}

code:focus {
  animation: select 100ms step-end forwards;
}

@keyframes select {
  to {
    -webkit-user-select: text;
    user-select: text;
  }
}

🐛 As noted in the comments by Kel: this animation-hack doesn’t work in Safari.

I’ve extended his example to re-enable user-select: all; whenever the snippet is blurred, so that upon a next selection it will restart with selecting all again. Feels more natural.

See the Pen Select All… Then Select Some by Bramus (@bramus) on CodePen.

🤔 This looks like something that should be added to the CSS Spec. It would require a new value for user-select, as user-select: all; explicitly says that all must be selected:

If a selection would contain part of the element, then the selection must contain the entire element including all its descendants.

Using CSS to Control Text Selection →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

3 Comments

  1. ::sad-trombone:: for Safari users. Doesn’t appear to work in v 13.1 under macOS 10.15.4

    1. Good Catch! What I’m seeing is that user-select: all; works in Safari (same versions) but the animation-hack doesn’t. Do you see the same?

      I’ll update the post to include a note on this, thanks!

Leave a comment

Leave a Reply to Kel Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.