Свойство user-select
управляет поведением выделения текста и других элементов на странице, в частности, позволяет запретить выделение текста.
Обычно применяется для интерактивных элементов, на которые можно щёлкать, например, вкладки, и для которых выделение текста нежелательно.
Демо¶
Интерфейс
- appearance
- box-sizing
- caret-color
- cursor
- outline
- outline-width
- outline-style
- outline-color
- outline-offset
- resize
- text-overflow
- user-select
Синтаксис¶
/* Keyword values */
user-select: none;
user-select: auto;
user-select: text;
user-select: contain;
user-select: all;
/* Global values */
user-select: inherit;
user-select: initial;
user-select: unset;
/* Mozilla-specific values */
-moz-user-select: none;
-moz-user-select: text;
-moz-user-select: all;
/* WebKit-specific values */
-webkit-user-select: none;
-webkit-user-select: text;
/* Doesn't work in Safari; use only
"none" or "text", or else it will
allow typing in the <html> container */
-webkit-user-select: all;
/* Microsoft-specific values */
-ms-user-select: none;
-ms-user-select: text;
-ms-user-select: element;
Значения¶
auto
- Для редактируемых элементов значение принимается
contain
. Если у родителя значениеuser-select
установлено какall
, то для элемента оно тоже будетall
. Если у родителя значениеuser-select
установлено какnone
, то для элемента оно тоже будетnone
. Во всех остальных случаях принимается значениеtext
. none
- Пользователю запрещено выделять элемент.
text
- Пользователь может выделить текст в элементе.
all
- Позволяет выделить текст внутри элемента, включая дочерние элементы.
contain
- Позволяет выделять текст, но только внутри границ элемента.
Примечание¶
- Internet Explorer поддерживает свойство
-ms-user-select
. - Chrome, Opera, Safari и Android поддерживают свойство
-webkit-user-select
. - Firefox поддерживает свойство
-moz-user-select
. - Значение
contain
поддерживается только в IE.
Значение по-умолчанию: auto
Применяется ко всем элементам
Спецификации¶
- CSS Basic User Interface Module Level 4
Поддержка браузерами¶
Can I Use user-select-none? Data on support for the user-select-none feature across the major browsers from caniuse.com.
Описание и примеры¶
<html>
<head>
<meta charset="utf-8" />
<title>user-select</title>
<style>
body {
-ms-user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
user-select: none;
}
.enable {
-ms-user-select: all;
-moz-user-select: all;
-webkit-user-select: all;
user-select: all;
}
</style>
</head>
<body>
<p>Этот текст нельзя выделить</p>
<p>
<input
type="text"
value="Этот текст можно выделить"
/>
</p>
<p class="enable">
Этот <b>текст</b> тоже можно выделить
</p>
</body>
</html>
Управляет поведением выделения текста и других элементов на странице, в частности, позволяет запретить выделение текста. Обычно применяется для интерактивных элементов, на которые можно щёлкать, например, вкладки, и для которых выделение текста нежелательно.
Краткая информация
Значение по умолчанию | auto |
---|---|
Наследуется | Да |
Применяется | Ко всем элементам |
Процентная запись | Неприменима |
Анимируется | Нет |
Синтаксис
user-select: auto | none | text | all | contain
Синтаксис
Описание | Пример | |
---|---|---|
<тип> | Указывает тип значения. | <размер> |
A && B | Значения должны выводиться в указанном порядке. | <размер> && <цвет> |
A | B | Указывает, что надо выбрать только одно значение из предложенных (A или B). | normal | small-caps |
A || B | Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. | width || count |
[ ] | Группирует значения. | [ crop || cross ] |
* | Повторять ноль или больше раз. | [,<время>]* |
+ | Повторять один или больше раз. | <число>+ |
? | Указанный тип, слово или группа не является обязательным. | inset? |
{A, B} | Повторять не менее A, но не более B раз. | <радиус>{1,4} |
# | Повторять один или больше раз через запятую. | <время># |
Значения
- auto
- Для редактируемых элементов значение принимается contain. Если у родителя значение user-select установлено как all, то для элемента оно тоже будет all. Если у родителя значение user-select установлено как none, то для элемента оно тоже будет none. Во всех остальных случаях принимается значение text.
- none
- Пользователю запрещено выделять элемент.
- text
- Пользователь может выделить текст в элементе.
- all
- Позволяет выделить текст внутри элемента, включая дочерние элементы.
- contain
- Позволяет выделять текст, но только внутри границ элемента.
Пример
<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>user-select</title>
<style>
body {
user-select: none;
}
.enable {
user-select: all;
}
</style>
</head>
<body>
<p>Этот текст нельзя выделить</p>
<p><input type=»text» value=»Этот текст можно выделить»></p>
<p class=»enable»>Этот <b>текст</b> тоже можно выделить</p>
</body>
</html>
Примечание
Internet Explorer и Edge поддерживают свойство -ms-user-select.
Chrome до версии 54, Opera до версии 41, Safari и Android поддерживают свойство -webkit-user-select.
Firefox поддерживает свойство -moz-user-select.
Значение contain поддерживается только в IE.
Спецификация
Спецификация | Статус |
---|---|
CSS Basic User Interface Module Level 4 | Редакторский черновик |
Спецификация
Каждая спецификация проходит несколько стадий одобрения.
- Recommendation (Рекомендация) — спецификация одобрена W3C и рекомендована как стандарт.
- Candidate Recommendation (Возможная рекомендация) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта.
- Proposed Recommendation (Предлагаемая рекомендация) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения.
- Working Draft (Рабочий проект) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом.
- Editor’s draft (Редакторский черновик) — черновая версия стандарта после внесения правок редакторами проекта.
- Draft (Черновик спецификации) — первая черновая версия стандарта.
Браузеры
10 | 12 | 4 | 54 | 15 | 41 | 3.1 | 2 |
Браузеры
В таблице браузеров применяются следующие обозначения.
- — элемент полностью поддерживается браузером;
- — элемент браузером не воспринимается и игнорируется;
- — при работе возможно появление различных ошибок, либо элемент поддерживается с оговорками.
Число указывает версию браузреа, начиная с которой элемент поддерживается.
DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!
The user-select
property in CSS controls how the text in an element is allowed to be selected. For example, it can be used to make text unselectable.
.row-of-icons {
-webkit-user-select: none; /* Chrome all / Safari all */
-moz-user-select: none; /* Firefox all */
-ms-user-select: none; /* IE 10+ */
user-select: none; /* Likely future */
}
This is useful in situations where you want to provide an easier/cleaner copy-paste experience for users (not have them accidentally text-select useless things, like icons or images). However it’s a bit buggy. Firefox enforces the fact that any text matching that selector cannot be copied. WebKit still allows the text to be copied if you select elements around it.
You can also use this to enforce that an entire element gets selection:
.force-select {
-webkit-user-select: all; /* Chrome 49+ */
-moz-user-select: all; /* Firefox 43+ */
-ms-user-select: all; /* No support yet */
user-select: all; /* Likely future */
}
Here’s some demos of those:
See the Pen user-select demo by Chris Coyier (@chriscoyier) on CodePen.
There was no spec for this property for quite a while, but now is covered under CSS Basic User Interface Module Level 4.
The default value is auto
, which makes selection happen normally as you expect. “Normally” is a bit complicated. It’s worth quoting from the spec here:
- On the ::before and ::after pseudo elements, the computed value is
none
- If the element is an editable element, the computed value is
contain
- Otherwise, if the computed value of user-select on the parent of this element is
all
, the computed value isall
- Otherwise, if the computed value of user-select on the parent of this element is
none
, the computed value isnone
- Otherwise, the computed value is
text
In other words, it intelligently cascades and resets to a sensical state. It looks like maybe this feature could be used to make pseudo elements selectable, but no final word yet.
Older/Proprietary
Firefox supports -moz-none
, which is just like none except that it means sub-elements can override the cascade and become selectable again with -moz-user-select: text;
As of Firefox 21, none behaves like -moz-none
.
Internet Explorer also supports a so-far-proprietary value, element
, in which you can select text inside the element but the selection will stop at the bounds of that element.
More Information
- MDN Docs
- User Select interoperability
Browser Support
This is specifically for -*-user-select: none;
Desktop
Chrome | Firefox | IE | Edge | Safari |
---|---|---|---|---|
4* | 2* | 10* | 12* | 3.1* |
Mobile / Tablet
Android Chrome | Android Firefox | Android | iOS Safari |
---|---|---|---|
113 | 113 | 2.1* | 3.2* |
Internet Explorer поддерживает свойство -ms-user-select.
Chrome, Opera, Safari и Android поддерживают свойство -webkit-user-select.
Firefox поддерживает свойство -moz-user-select.
Значение contain поддерживается только в IE.
Чаще всего CSS стиль user-select применяется для кликабельных интерактивных элементов, для которых нежелательно выделение текста.
Краткая информация по CSS-свойству user-select
Значение по умолчанию | auto |
---|---|
Наследуется | Да |
Применяется | Ко всем элементам |
Правила написания свойства user-select
user-select: auto | none | text | all | contain
Пройдемся теперь по всем значениям.
auto
— для редактируемых элементов значение принимается contain. Если у родительского элемента user-select установлено как all (none), то для элемента оно тоже будет all (none). Во всех остальных случаях принимается значение text.
none
— пользователю запрещается выделять элемент.
text
— пользователь может выделить текст в элементе.
all
— позволяет выделить текст внутри элемента, включая дочерние элементы.
contain
— позволяет выделять текст, но лишь внутри элемента.
Пример применения стиля user-select
Проиллюстрируем работу user-select на примере. Давайте сделаем так, чтобы верхний текст нельзя было выделить. Не забудьте про кроссбраузерное написание user-select.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Пример CSS стиля user-select</title>
<style>
body {
-ms-user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
user-select: none;
}
.enable {
-ms-user-select: all;
-moz-user-select: all;
-webkit-user-select: all;
user-select: all;
}
</style>
</head>
<body>
<p>Ха! А этот текст нельзя выделить</p>
<p><input type="text" value="Этот текст выделяется"></p>
<p class="enable">Этот текст тоже выделяется</p>
</body>
</html>
The user-select property specifies whether or not the user can select text.
The default value is «auto» which is determined as follows:
- On the ::before and ::after pseudo elements, the computed value is «none»
- If the element is an editable element, the computed value is «contain»,
- If the computed value of user-select on the parent of this element is «all», the computed value is «all».
- If the computed value of user-select on the parent of this element is «none», the computed value is «none»,
- Otherwise, the computed value is «text».
For maximum browser compatibility extensions such as -webkit-
for Safari, Google Chrome, and Opera (newer versions), -moz- for Firefox are used with this property.
user-select: auto | none | text | all | contain | initial | inherit;
Example of the user-select property with the «auto» value:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
div {
-webkit-user-select: auto;/* Safari 3.1+ */
-moz-user-select: auto;/* Firefox 2+ */
user-select: auto;/* Standard syntax */
}
</style>
</head>
<body>
<h2>User-select property example</h2>
<div>Lorem ipsum is simply dummy text.</div>
</body>
</html>
In the given example, the text cannot be selected.
Example of the user-select property with the «none» value:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
div {
-webkit-user-select: none;/* Safari 3.1+ */
-moz-user-select: none;/* Firefox 2+ */
user-select: none;/* Standard syntax */
}
</style>
</head>
<body>
<h2>User-select property example</h2>
<div>Lorem ipsum is simply dummy text.</div>
</body>
</html>
The text is selected by one click instead of double-click.
Example of the user-select property with the «all» value:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
div {
-webkit-user-select: all;/* Safari 3.1+ */
-moz-user-select: all;/* Firefox 2+ */
user-select: all;/* Standard syntax */
}
</style>
</head>
<body>
<h2>User-select property example</h2>
<div>Lorem ipsum is simply dummy text.</div>
</body>
</html>
In the following example, you can select any part of the text you want.
Example of the user-select property with the «text» value:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
div {
-webkit-user-select: text;/* Safari 3.1+ */
-moz-user-select: text;/* Firefox 2+ */
user-select: text;/* Standard syntax */
}
</style>
</head>
<body>
<h2>User-select property example</h2>
<div>Lorem ipsum is simply dummy text.</div>
</body>
</html>