Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent element from taking part in text selection

I have some source code in a <pre><code> with line numbers in a separate <div>. When the text is selected, the line numbers come with it, and are subsequently copied. Is there any way to prevent the line numbers from being a part of the selection, even if I select the elements above and below the source code block?

I'd like to avoid JavaScript for the benefit of people who browse with it off. (With JavaScript, I'd add a button to hide the line numbers).

unselectable="on" and the various vendor-specific user-select CSS properties did not work; the numbers are still selected and copied.

like image 897
nneonneo Avatar asked Mar 01 '13 06:03

nneonneo


People also ask

How do you prevent user from selecting the text rendered inside the element?

You can use the user-select property to disable text selection of an element. In web browsers, if you double-click on some text it will be selected/highlighted. This property can be used to prevent this.

How can I prevent text element selection with cursor drag?

Try applying user-select: none to an element and dragging over it.

How do I stop text selection?

To disable text selection highlighting in Google Chrome browser using CSS just set -user-select CSS property to none. And no prefix is required for Google Chrome and Opera Browsers.


1 Answers

Give the element you want to prevent selection of an id.

Then put this in your CSS:

#id-name {
   -webkit-touch-callout: none;
   -webkit-user-select: none;
   -khtml-user-select: none;
   -moz-user-select: none;
   -ms-user-select: none;
   user-select: none;
}
::-moz-selection {
   background: transparent;
}
::selection { 
   background: transparent; 
}
like image 58
Phillip Berger Avatar answered Sep 21 '22 21:09

Phillip Berger