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 Freelance Web Developer from Belgium. 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. 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 Bramus! 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.