Cursor error css

The cursor CSS property specifies the mouse cursor displayed when the mouse pointer is over an element.

Курсор

Описание

The cursor CSS property specifies the mouse cursor displayed when the mouse pointer is over an element.

Начальное значение auto
Применяется к все элементы
Наследуется да
Обработка значения как указано, но с абсолютными значениями url
Animation type discrete

Синтаксис

/* Применение ключевых значений */
cursor: pointer;
cursor: auto;

/* Использование URL и координат */
cursor:  url(cursor1.png) 4 12, auto;
cursor:  url(cursor2.png) 2 2, pointer;

/* Глобальные значения */
cursor: inherit;
cursor: initial;
cursor: unset;

Значения

<url>

Ссылка или разделённый запятыми список ссылок: url(…), url(…), …, указывающие на файл изображения. Дополнительные ссылки могут быть предоставлены в качестве запасных значений, на случай если изображение по основной ссылке не поддерживается в качестве курсора. Запасное значение, не являющееся ссылкой (одно или несколько ключевых слов) должно находиться в конце списка значений. See Using URL values for the cursor property for more details.

<x> <y>
Экспериментальная возможность

Необязательные значения х- и у- координат. Два безразмерных неотрицательных числа меньше 32.

Ключевые слова

Наведите курсор на картинку, чтобы увидеть пример в действии:

Категория Значение Вид Описание
Основные auto Браузер самостоятельно определяет значение курсора в зависимости от
свойств элемента, на который наведена мышь.
Например: при наведении
на текст отобразит курсор text.
default default.gif Основной курсор платформы, обычно стрелочка.
none Курсор не отображается.
Ссылки и статусы выполнения задач context-menu context-menu.png Доступно контекстное меню.
help help.gif Доступна вспомогательная информация.
pointer pointer.gif Указатель, обозначающий ссылку, обычно указующая рука.
progress progress.gif Программа занята, но пользователь может взаимодействовать с интерфейсом
(в отличие от wait).
wait wait.gif Программа занята (песочные часы).
Выделение cell cell.gif Указывает на возможность выбора клетки или клеток таблицы.
crosshair crosshair.gif Крестик, часто используемый для обозначения выбора на битовой карте.
text text.gif Значок выбора текста.
vertical-text vertical-text.gif Значок выбора вертикального текста.
«Захвати и перенеси» alias alias.gif Будет создана ссылка внутри страницы.
copy copy.gif Указывает на возможность копирования.
move move.gif

Указывает на возможность перемещения объекта.

no-drop no-drop.gif Указывает на невозможность «сбрасывания» объекта.
В Windows и Mac
OSX то же самое что и not-allowed.
not-allowed not-allowed.gif Указатель невозможности выполнения действия.
Изменение размера, прокручивание (скроллинг) all-scroll all-scroll.gif Указатель возможности перемещения по странице в любом направлении.
в
Windows то же самое что move.
col-resize col-resize.gif Объект может быть раздвинут/сдвинут горизонтально. Обычно две
вертикальные черты со стрелочками в разные стороны.
row-resize row-resize.gif Объект может быть раздвинут/сдвинут вертикально. Две горизонтальные
черты с вертикальными стрелочками.
n-resize Example of a resize towards the top cursor Грань или грани могут быть перемещены. Например
se-resize используется для обозначения перемещения с
юго-востока. В некоторых системах то же самое что двунаправленное
изменение.
e-resize Example of a resize towards the right cursor
s-resize Example of a resize towards the bottom cursor
w-resize Example of a resize towards the left cursor
ne-resize Example of a resize towards the top-right corner cursor
nw-resize Example of a resize towards the top-left corner cursor
se-resize Example of a resize towards the bottom-right corner cursor
sw-resize Example of a resize towards the bottom-left corner cursor
ew-resize 3-resize.gif Двунаправленное изменение размера.
ns-resize 6-resize.gif
nesw-resize 1-resize.gif
nwse-resize 4-resize.gif
Масштабирование zoom-in zoom-in.gif

Приближение или уменьшение.

zoom-out zoom-out.gif
Захват grab grab.gif

Указывает на возможность схватить и переместить объект.

grabbing grabbing.gif

Формальный синтаксис

Примеры

.foo {
  cursor: crosshair;
}

/* use prefixed-value if "zoom-in" isn't supported */
.bar {
  cursor: -webkit-zoom-in;
  cursor: zoom-in;
}

/* standard cursor value as fallback for url() must be provided (doesn't work without) */
.baz {
  cursor: url(hyper.cur), auto;
}

Спецификации

Specification
CSS Basic User Interface Module Level 4
# cursor

Совместимость с браузерами

BCD tables only load in the browser

Смотрите также

Устанавливает форму курсора, когда он находится в пределах элемента. Вид курсора зависит от операционной системы и установленных параметров.

Краткая информация

Значение по умолчанию auto
Наследуется Да
Применяется Ко всем элементам
Анимируется Нет

Синтаксис

cursor: [url('адрес'),] | [ <курсор> ]

Синтаксис

Описание Пример
<тип> Указывает тип значения. <размер>
A && B Значения должны выводиться в указанном порядке. <размер> && <цвет>
A | B Указывает, что надо выбрать только одно значение из предложенных (A или B). normal | small-caps
A || B Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. width || count
[ ] Группирует значения. [ crop || cross ]
* Повторять ноль или больше раз. [,<время>]*
+ Повторять один или больше раз. <число>+
? Указанный тип, слово или группа не является обязательным. inset?
{A, B} Повторять не менее A, но не более B раз. <радиус>{1,4}
# Повторять один или больше раз через запятую. <время>#

Значения

url
Позволяет установить свой собственный курсор, для этого нужно указать путь к файлу с курсором.
auto
Вид курсора по умолчанию для текущего элемента.
none
Отключает отображение курсора.

Остальные допустимые значения приведены в табл. 1. Чтобы увидеть как курсор выглядит в реальности, наведите на колонку Тест.

Табл. 1. Вид курсора

Вид Значение Тест Пример Примечание
default P {cursor: default}  
context-menu P {cursor: context-menu} Отображается только в IE10+.
help P {cursor: help}  
pointer P {cursor: pointer}  
progress P {cursor: progress}  
wait P {cursor: wait}  
cell P {cursor: cell}  
crosshair P {cursor: crosshair}  
text P {cursor: text}  
vertical-text P {cursor: vertical-text}  
alias P {cursor: alias}  
copy P {cursor: copy}  
move P {cursor: move}  
no-drop P {cursor: no-drop} Все браузеры, кроме IE, отображают как not-allowed.
not-allowed P {cursor: not-allowed}  
all-scroll P {cursor: all-scroll}  
col-resize P {cursor: col-resize}  
row-resize P {cursor: row-resize}  
n-resize P {cursor: n-resize}  
ne-resize P {cursor: ne-resize}  
e-resize P {cursor: e-resize}  
se-resize P {cursor: se-resize}  
s-resize P {cursor: s-resize}  
sw-resize P {cursor: sw-resize}  
w-resize P {cursor: w-resize}  
nw-resize P {cursor: nw-resize}  
nesw-resize P {cursor: nesw-resize}  
nwse-resize P {cursor: nwse-resize}  
zoom-in P {cursor: zoom-in} IE не поддерживает.
zoom-out P {cursor: zoom-out} IE не поддерживает.
grab P {cursor: grab} Chrome, Opera, Safari поддерживают значение -webkit-grab. IE не поддерживает.
grabbing P {cursor: grabbing} Chrome, Opera, Safari поддерживают значение -webkit-grabbing. IE не поддерживает.

В зависимости от операционной системы и её настроек вид курсора может отличаться
от приведённых в таблице.

При добавлении курсора из файла синтаксис несколько видоизменится.

cursor: url(<адрес>), url(<адрес>), ..., <курсор>

Через запятую допускается указывать несколько значений url, в этом случае браузер попытается открыть первый файл с курсором и если это по каким-либо причинам не получится, перейдёт к следующему файлу. Список обязательно заканчивается ключевым словом, например, auto или pointer, допустимые значения перечислены выше.

Пример

<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>cursor</title>
<style>
.cross { cursor: crosshair; }
.help { cursor: help; }
</style>
</head>
<body>
<p class=»cross»>На этом тексте курсор мыши примет вид перекрестья.</p>
<p>
<a href=»page/help.html» class=»help»>СПРАВКА 1</a><br>
<a href=»page/help.html» class=»help»>СПРАВКА 2</a><br>
<a href=»page/help.html» class=»help»>СПРАВКА 3</a>
</p>
</body>
</html><!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>cursor</title>
<style>
a { cursor: url(/example/cursor/sniper.cur), pointer; }
</style>
</head>
<body>
<p>Обычный текст</p>
<p><a href=»page/1.html»>Ссылка 1</a> <a href=»page/2.html»>Ссылка 2</a>
<a href=»page/3.html»>Ссылка 3</a></p>
</body>
</html>

Объектная модель

Объект.style.cursor

Примечание

Internet Explorer в качестве формата файла курсора поддерживает CUR и ANI. Firefox, Chrome, Safari поддерживают форматы CUR, PNG, GIF, JPG.

Chrome до версии 36, Opera до версии 24 и Safari до версии 9 поддерживают значения -webkit-zoom-in и -webkit-zoom-out.

Firefox до версии 24 поддерживает значения -moz-zoom-in и -moz-zoom-out.

Chrome до версии 22, Opera до версии 24 и Safari до версии 9 поддерживают значения -webkit-grab и -webkit-grabbing.

Firefox до версии 27 поддерживает значения -moz-grab и -moz-grabbing.

Браузеры на мобильных устройствах не поддерживают свойство cursor.

Спецификация

Спецификация Статус
CSS Basic User Interface Module Level 3 Рабочий проект
CSS Level 2 (Revision 1) Рекомендация

Спецификация

Каждая спецификация проходит несколько стадий одобрения.

  • Recommendation (Рекомендация) — спецификация одобрена W3C и рекомендована как стандарт.
  • Candidate Recommendation (Возможная рекомендация) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта.
  • Proposed Recommendation (Предлагаемая рекомендация) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения.
  • Working Draft (Рабочий проект) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом.
  • Editor’s draft (Редакторский черновик) — черновая версия стандарта после внесения правок редакторами проекта.
  • Draft (Черновик спецификации) — первая черновая версия стандарта.

Браузеры

auto, crosshair, default, move, text, wait, help, n-resize, e-resize, s-resize, w-resize, ne-resize, nw-resize, se-resize, sw-resize 4 12 1 7 1.2 1
pointer, progress 6 12 1 7 1.2 1
url() 6 12 1 15 3 1.5
not-allowed, no-drop, vertical-text, all-scroll, col-resize, row-resize 6 12 1 10.6 3 1.5
alias, cell, copy, ew-resize, ns-resize, nesw-resize, nwse-resize, context-menu 10 12 1 10.6 3 1.5
none 6 14 5 15 5 3
zoom-in, zoom-out 12 4 36 15 24 3.1 9 2 24
grab, grabbing 12 4 22 15 24 4 9 1.5 27

Браузеры

В таблице браузеров применяются следующие обозначения.

  • — элемент полностью поддерживается браузером;
  • — элемент браузером не воспринимается и игнорируется;
  • — при работе возможно появление различных ошибок, либо элемент поддерживается с оговорками.

Число указывает версию браузреа, начиная с которой элемент поддерживается.

Internet Explorer Chrome Opera Safari Firefox Android iOS
6.0 1.0+ 7.0+ 15.0+ 3.0+ 1.5+ 1.0+ 1.0+

Краткая информация

Значение по умолчанию auto
Наследуется Да
Применяется Ко всем элементам
Ссылка на спецификацию http://www.w3.org/TR/CSS21/ui.html#cursor-props

Версии CSS

CSS 1 CSS 2 CSS 2.1 CSS 3

Описание

Устанавливает форму курсора, когда он находится в пределах элемента. Вид курсора
зависит от операционной системы и установленных параметров.

Прежде чем воспользоваться возможностью переделать вид курсора, решите, а
будет ли он использоваться к месту. Многих пользователей подобные изменения
могут ввести в заблуждение, когда, например, вместо традиционной руки, появляющейся
при наведении на ссылку, возникает нечто другое. В большинстве случаев, лучше
оставить все как есть.

Синтаксис

cursor: [url(‘путь к курсору’),] | [ auto | crosshair | default | e-resize | help | move
| n-resize | ne-resize | nw-resize | pointer | progress | s-resize | se-resize
| sw-resize | text | w-resize | wait | inherit ]

Значения

url
Позволяет установить свой собственный
курсор, для этого нужно указать путь к файлу с курсором.
auto
Вид курсора по умолчанию для текущего элемента.
inherit
Наследует значение родителя.

Остальные допустимые значения приведены в табл. 1.

Табл. 1. Вид курсора

Вид Значение Тест Пример
default P {cursor: default}
crosshair P {cursor: crosshair}
help P {cursor: help}
move P {cursor: move}
pointer P {cursor: pointer}
progress P {cursor: progress}
text P {cursor: text}
wait P {cursor: wait}
n-resize P {cursor: n-resize}
ne-resize P {cursor: ne-resize}
e-resize P {cursor :e-resize}
 / se-resize P {cursor: se-resize}
s-resize P {cursor: s-resize}
sw-resize P {cursor: sw-resize}
w-resize P {cursor: w-resize}
nw-resize P {cursor :nw-resize}

В зависимости от операционной системы и ее настроек вид курсора может отличаться
от приведенных в таблице.

При добавлении курсора из файла синтаксис несколько видоизменится.

cursor: url(‘путь к курсору1’), url(‘путь к курсору2’), …, <ключевое слово>

Через запятую допускается указывать несколько значений url, в этом случае браузер попытается открыть первый файл с курсором и если это по каким-либо причинам не получится, перейдет к следующему файлу. Список обязательно заканчивается ключевым словом, например, auto или pointer, допустимые значения перечислены выше.

Пример 1

HTML5CSS2.1IECrOpSaFx

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>cursor</title>
  <style>
   .cross { cursor: crosshair; }
   .help { cursor: help; }
  </style>
 </head> 
 <body>
  <p class="cross">На этом тексте курсор мыши примет вид перекрестья.</p>
  <p> 
   <a href="help.html" class="help">СПРАВКА 1</a><br />
   <a href="help.html" class="help">СПРАВКА 2</a><br />
   <a href="help.html" class="help">СПРАВКА 3</a>
  </p> 
 </body>
</html>

Результат данного примера показан на рис. 1.

Применение свойства cursor

Рис. 1. Применение свойства cursor

Пример 2

HTML5CSS2.1IECrOpSaFx

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>cursor</title>
  <style>
   a { cursor: url(images/sniper.cur), pointer; }
  </style>
 </head> 
 <body>
  <p>Обычный текст</p>
  <p><a href="1.html">Ссылка 1</a> <a href="2.html">Ссылка 2</a>
   <a href="3.html">Ссылка 3</a></p> 
 </body>
</html>

Объектная модель

[window.]document.getElementById(«elementID«).style.cursor

Браузеры

Некоторые браузеры поддерживают дополнительные формы курсоров. Например, Internet
Explorer и Opera работает со значением hand, которое является
аналогом значения pointer. Кроме того, в
браузерах Safari, Chrome и Firefox будут действовать следующие значения: all-scroll,
col-resize, no-drop,
not-allowed, row-resize,
vertical-text. Учтите, что указанные значения не входят в спецификацию CSS 2.1, но соответствуют спецификации CSS3 (кроме hand).

Internet Explorer в качестве формата файла курсора поддерживает CUR и ANI. Firefox, Chrome, Safari поддерживают форматы CUR, PNG, GIF, JPG.

Opera не работает с файлами курсора.


Contents

  • 18.1 Cursors: the ‘cursor’ property
  • 18.2 System Colors
  • 18.3 User preferences for fonts
  • 18.4 Dynamic outlines: the ‘outline’ property
    • 18.4.1 Outlines and the focus
  • 18.5 Magnification

18.1 Cursors: the ‘cursor’ property

‘cursor’
Value:   [ [<uri> ,]* [ auto | crosshair | default | pointer | move | e-resize
| ne-resize | nw-resize | n-resize | se-resize | sw-resize | s-resize
| w-resize | text | wait | help | progress ] ] | inherit
Initial:   auto
Applies to:   all elements
Inherited:   yes
Percentages:   N/A
Media:   visual, interactive
Computed value:   as specified, except with any relative URLs converted to absolute

This property specifies the type of cursor to be displayed for the
pointing device. Values have the following meanings:

auto
The UA determines the cursor to display based on the current
context.
crosshair
A simple crosshair (e.g., short line segments resembling a «+» sign).
default
The platform-dependent default cursor. Often rendered as an arrow.
pointer
The cursor is a pointer that indicates a link.
move
Indicates something is to be moved.
e-resize, ne-resize, nw-resize, n-resize, se-resize,
sw-resize, s-resize, w-resize
Indicate that some edge is to be moved. For example, the
‘se-resize’ cursor is used when the movement starts from the
south-east corner of the box.
text
Indicates text that may be selected. Often rendered as an I-beam.
wait
Indicates that the program is busy and the user should
wait. Often rendered as a watch or hourglass.
progress
A progress indicator. The program is performing some processing,
but is different from ‘wait’ in that the user may still interact with the program.
Often rendered as a spinning beach ball,
or an arrow with a watch or hourglass.
help
Help is available for the object under the cursor. Often rendered
as a question mark or a balloon.
<uri>
The user agent retrieves the cursor from the resource
designated by the URI. If the user agent cannot handle
the first cursor of a list of cursors, it should attempt
to handle the second, etc. If the user agent cannot handle
any user-defined cursor, it must use the generic cursor
at the end of the list.
Intrinsic sizes for cursors are calculated as for background images, except
that a UA-defined rectangle is used in place of the rectangle that
establishes the coordinate system for the ‘background-image’ property.
This UA-defined rectangle should be based on the size of a typical
cursor on the UA’s operating system. If the resulting cursor size does
not fit within this rectangle, the UA may proportionally scale the
resulting cursor down until it fits within the rectangle.

:link,:visited { cursor: url(example.svg#linkcursor), url(hyper.cur), pointer }

This example sets the cursor on all hyperlinks (whether visited or not)
to an external SVG cursor.
User agents that do not support SVG cursors would simply skip to the
next value and attempt to use the «hyper.cur» cursor.
If that cursor format was also not supported, the UA would skip to the next value and simply render the ‘pointer’ cursor.

18.2 System Colors

Note.
The System Colors are deprecated in the CSS3 Color Module [CSS3COLOR].

In addition to being able to assign pre-defined color values to text, backgrounds, etc., CSS2 introduced a set of named color values that allows authors to specify colors in a manner that integrates them into the operating system’s graphic environment.

For systems that do not have a corresponding value, the
specified value should be mapped to the nearest system value, or to a default color.

The following lists additional values for color-related CSS properties and their general meaning. Any color property (e.g., ‘color’ or ‘background-color’) can take
one of the following names. Although these are case-insensitive, it is
recommended that the mixed capitalization shown below be used, to
make the names more legible.

ActiveBorder
Active window border.
ActiveCaption
Active window caption.
AppWorkspace
Background color of multiple document interface.
Background
Desktop background.
ButtonFace
Face color for three-dimensional display elements.
ButtonHighlight
Highlight color for three-dimensional display elements (for
edges facing away from the light source).
ButtonShadow
Shadow color for three-dimensional display elements.
ButtonText
Text on push buttons.
CaptionText
Text in caption, size box, and scrollbar arrow box.
GrayText
Grayed (disabled) text. This color is set to #000 if
the current display driver does not support a solid gray color.
Highlight
Item(s) selected in a control.
HighlightText
Text of item(s) selected in a control.
InactiveBorder
Inactive window border.
InactiveCaption
Inactive window caption.
InactiveCaptionText
Color of text in an inactive caption.
InfoBackground
Background color for tooltip controls.
InfoText
Text color for tooltip controls.
Menu
Menu background.
MenuText
Text in menus.
Scrollbar
Scroll bar gray area.
ThreeDDarkShadow
Dark shadow for three-dimensional display elements.
ThreeDFace
Face color for three-dimensional display elements.
ThreeDHighlight
Highlight color for three-dimensional display elements.
ThreeDLightShadow
Light color for three-dimensional display elements
(for edges facing the light source).
ThreeDShadow
Dark shadow for three-dimensional display elements.
Window
Window background.
WindowFrame
Window frame.
WindowText
Text in windows.

For example, to set the foreground and background colors of a paragraph
to the same foreground and background colors of the user’s window,
write the following:


p { color: WindowText; background-color: Window }

18.3 User preferences for fonts

As for colors, authors may specify fonts in a way that makes use of
a user’s system resources. Please consult the ‘font’ property for details.

18.4 Dynamic outlines: the ‘outline’ property

At times, style sheet authors may want to create outlines around
visual objects such as buttons, active form fields, image maps, etc.,
to make them stand out. CSS 2.1 outlines differ from borders in the following
ways:

  1. Outlines do not take up space.
  2. Outlines may be non-rectangular.

The outline properties control the style of these dynamic outlines.

The outline created with the outline properties is drawn «over» a
box, i.e., the outline is always on top, and does not influence the
position or size of the box, or of any other boxes. Therefore,
displaying or suppressing outlines does not cause reflow or overflow.

The outline may be drawn starting just outside the border edge.

Outlines may be non-rectangular. For example, if the element is
broken across several lines, the outline is the minimum outline that
encloses all the element’s boxes. In contrast to borders, the outline is not
open at the line box’s end or start, but is always fully connected if possible.

The ‘outline-width’
property accepts the same values as ‘border-width’.

The ‘outline-style’
property accepts the same values as ‘border-style’,
except that ‘hidden’ is not a legal outline style.

The ‘outline-color’
accepts all colors, as well as the keyword ‘invert’. ‘Invert’ is expected to
perform a color inversion on the pixels on the screen. This is a
common trick to ensure the focus border is visible, regardless of
color background.

Conformant UAs may ignore the ‘invert’ value on platforms that do not
support color inversion of the pixels on the screen. If the UA does not
support the ‘invert’ value then the initial value of the ‘outline-color’
property is the value of the ‘color’ property, similar to the initial value
of the ‘border-top-color’ property.

The ‘outline’ property is a
shorthand property, and sets all three of ‘outline-style’, ‘outline-width’, and ‘outline-color’.

Note.
The outline is the same on all sides. In
contrast to borders, there is no ‘outline-top’ or ‘outline-left’
property.

This specification does not define how multiple overlapping
outlines are drawn, or how outlines are drawn for boxes that are
partially obscured behind other elements.

Note.
Since the outline does not affect formatting (i.e., no
space is left for it in the box model), it may well overlap
other elements on the page.

Here’s an example of drawing a
thick outline around a BUTTON element:


button { outline : thick solid}

Scripts may be used to dynamically change the width
of the outline, without provoking a reflow.

18.4.1 Outlines and the focus

Graphical user interfaces may use outlines around elements to tell
the user which element on the page has the focus. These outlines are in addition
to any borders, and switching outlines on and off should not cause
the document to reflow. The focus is the subject of user interaction
in a document (e.g., for entering text, selecting a button,
etc.). User agents supporting the interactive media group
must keep track of where the focus lies and must also represent the
focus. This may be done by using dynamic outlines in conjunction with
the :focus pseudo-class.

For example, to draw a thick black line around an element when it
has the focus, and a thick red line when it is active, the following
rules can be used:


:focus  { outline: thick solid black }
:active { outline: thick solid red }

18.5 Magnification

The CSS working group considers that the magnification of a
document or portions of a document should not be specified through
style sheets. User agents may support such magnification in different ways
(e.g., larger images, louder sounds, etc.)

When magnifying a page, UAs should preserve the relationships
between positioned elements. For example, a comic strip may be
composed of images with overlaid text elements. When magnifying this
page, a user agent should keep the text within the comic strip balloon.


Example

CSS can generate a bunch of different mouse cursors:

.alias {cursor: alias;}
.all-scroll {cursor: all-scroll;}
.auto
{cursor: auto;}
.cell {cursor: cell;}
.col-resize {cursor: col-resize;}
.context-menu {cursor:
context-menu;}
.copy {cursor: copy;}
.crosshair {cursor: crosshair;}
.default {cursor: default;}
.e-resize
{cursor: e-resize;}
.ew-resize {cursor: ew-resize;}
.grab {cursor:
grab;}
.grabbing {cursor: grabbing;}
.help {cursor: help;}
.move
{cursor: move;}
.n-resize {cursor: n-resize;}
.ne-resize {cursor:
ne-resize;}
.nesw-resize {cursor: nesw-resize;}
.ns-resize {cursor:
ns-resize;}
.nw-resize {cursor: nw-resize;}
.nwse-resize {cursor: nwse-resize;}
.no-drop {cursor: no-drop;}
.none {cursor: none;}
.not-allowed
{cursor: not-allowed;}
.pointer {cursor: pointer;}
.progress {cursor:
progress;}
.row-resize {cursor: row-resize;}
.s-resize {cursor:
s-resize;}
.se-resize {cursor: se-resize;}
.sw-resize {cursor: sw-resize;}
.text {cursor: text;}
.url {cursor: url(myBall.cur),auto;}
.w-resize
{cursor: w-resize;}
.wait {cursor: wait;}
.zoom-in {cursor: zoom-in;}
.zoom-out {cursor: zoom-out;}

Try it Yourself »


Definition and Usage

The cursor property specifies the mouse cursor to be displayed when pointing over an element.

Default value: auto
Inherited: yes
Animatable: no. Read about animatable
Version: CSS2
JavaScript syntax: object.style.cursor=»crosshair»
Try it

Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Property
cursor 5.0 5.5 4.0 5.0 9.6


CSS Syntax

Property Values

Value Description Demo
alias The cursor indicates an alias of something is to be created Play it »
all-scroll The cursor indicates that something can be scrolled in any direction Play it »
auto Default. The browser sets a cursor Play it »
cell The cursor indicates that a cell (or set of cells) may be selected Play it »
col-resize The cursor indicates that the column can be resized horizontally Play it »
context-menu The cursor indicates that a context-menu is available Play it »
copy The cursor indicates something is to be copied Play it »
crosshair The cursor render as a crosshair Play it »
default The default cursor Play it »
e-resize The cursor indicates that an edge of a box is to be moved right (east) Play it »
ew-resize Indicates a bidirectional resize cursor Play it »
grab The cursor indicates that something can be grabbed Play it »
grabbing The cursor indicates that something can be grabbed Play it »
help The cursor indicates that help is available Play it »
move The cursor indicates something is to be moved Play it »
n-resize The cursor indicates that an edge of a box is to be moved up (north) Play it »
ne-resize The cursor indicates that an edge of a box is to be moved up and right (north/east) Play it »
nesw-resize Indicates a bidirectional resize cursor Play it »
ns-resize Indicates a bidirectional resize cursor Play it »
nw-resize The cursor indicates that an edge of a box is to be moved up and left (north/west) Play it »
nwse-resize Indicates a bidirectional resize cursor Play it »
no-drop The cursor indicates that the dragged item cannot be dropped here Play it »
none No cursor is rendered for the element Play it »
not-allowed The cursor indicates that the requested action will not be executed Play it »
pointer The cursor is a pointer and indicates a link Play it »
progress The cursor indicates that the program is busy (in progress) Play it »
row-resize The cursor indicates that the row can be resized vertically Play it »
s-resize The cursor indicates that an edge of a box is to be moved down (south) Play it »
se-resize The cursor indicates that an edge of a box is to be moved down and right (south/east) Play it »
sw-resize The cursor indicates that an edge of a box is to be moved down and left (south/west) Play it »
text The cursor indicates text that may be selected Play it »
URL A comma separated list of URLs to custom cursors. Note: Always specify a generic cursor at the end of the list, in case none of the URL-defined cursors can be used Play it »
vertical-text The cursor indicates vertical-text that may be selected Play it »
w-resize The cursor indicates that an edge of a box is to be moved left (west) Play it »
wait The cursor indicates that the program is busy Play it »
zoom-in The cursor indicates that something can be zoomed in Play it »
zoom-out The cursor indicates that something can be zoomed out Play it »
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Related Pages

HTML DOM reference: cursor property

cursor

Свойство CSS cursor устанавливает курсор мыши, если он есть, для отображения, когда указатель мыши находится над элементом.

Настройка курсора должна информировать пользователей об операциях мыши, которые можно выполнять в текущем местоположении, включая: выделение текста, активацию справки или контекстных меню, копирование содержимого, изменение размера таблиц и т. д. Вы можете указать либо тип курсора, используя ключевое слово, либо загрузить определенный значок для использования (с необязательными резервными изображениями и обязательным ключевым словом в качестве окончательного резерва).

Try it

Syntax

cursor: auto;
cursor: pointer;

cursor: zoom-out;


cursor: url(hand.cur), pointer;


cursor: url(cursor_1.png) 4 12, auto;
cursor: url(cursor_2.png) 2 2, pointer;


cursor: url(cursor_1.svg) 4 5, url(cursor_2.svg),  url(cursor_n.cur) 5 5, progress;


cursor: inherit;
cursor: initial;
cursor: revert;
cursor: revert-layer;
cursor: unset;

Свойство cursor задается как ноль или более значений <url> , разделенных запятыми, за которыми следует одно обязательное значение ключевого слова. Каждый <url> должен указывать на файл изображения. Браузер попытается загрузить первое указанное изображение, вернувшись к следующему, если не может, и вернется к значению ключевого слова, если изображения не могут быть загружены (или если ни одно из них не было указано).

За каждым <url> может дополнительно следовать пара чисел, разделенных пробелами, которые устанавливают координаты <x> <y> точки доступа курсора относительно левого верхнего угла изображения.

Values

<url>Optional

url() или разделенный запятыми список url url(), url(), … , указывающий на файл изображения. В качестве запасных вариантов может быть предоставлено более одного url() на случай, если некоторые типы изображений курсора не поддерживаются. Резервный вариант без URL (одно или несколько значений ключевого слова) должен быть в конце списка резервных вариантов.

<x><y>Optional

Необязательные x-и y-координаты,указывающие на «горячую точку» курсора;точная позиция в курсоре,на которую указывают.

Числа указаны в единицах пикселей изображения. Они относятся к верхнему левому углу изображения, что соответствует « 0 0 », и фиксируются в границах изображения курсора. Если эти значения не указаны, они могут быть прочитаны из самого файла, в противном случае по умолчанию они будут в верхнем левом углу изображения.

keyword

Необходимо указать значение ключевого слова , указывающее либо тип используемого курсора, либо резервный курсор, который следует использовать, если все указанные значки не загружаются.

Доступные ключевые слова перечислены в таблице ниже. Кроме none , что означает отсутствие курсора, есть изображение, показывающее, как раньше отображались курсоры. Вы можете навести указатель мыши на строки таблицы, чтобы увидеть влияние различных значений ключевых слов курсора на ваш браузер сегодня.

Category Keyword Example Description
General auto UA будет определять курсор для отображения на основе текущего контекста. Например, эквивалент text при наведении текста.
default wide arrow pointing up and to the left Курсор по умолчанию,зависящий от платформы.Обычно это стрелка.
none Курсор не выводится.
Ссылки и статус context-menu wide arrow pointing up and to the left slightly obscuring a menu icon Доступно контекстное меню.
help wide arrow pointing up and to the left next to a question mark Справочная информация доступна.
pointer right hand with an index finger pointing up Курсор-это указатель,указывающий на ссылку.Обычно это изображение указывающей руки.
progress wide arrow and hour glass Программа занята в фоновом режиме, но пользователь все равно может взаимодействовать с интерфейсом (в отличие от wait ).
wait hour glass Программа занята, и пользователь не может взаимодействовать с интерфейсом (в отличие от progress ). Иногда изображение песочных часов или часов.
Selection cell wide plus symbol Можно выбрать ячейку таблицы или набор ячеек.
crosshair plus symbol composed of two thing lines. Кросс-курсор,часто используемый для указания выделения в растровой карте.
text vertical i-beam Текст может быть выделен.Обычно это форма I-луча.
vertical-text horizontal i-beam Можно выбрать вертикальный текст.Обычно это форма бокового I-образного луча.
Перетаскивания alias wide arrow pointing up and to the left partially obscuring a smaller folder icon with a curved arrow pointing up and to the right Необходимо создать псевдоним или ярлык.
copy wide arrow pointing up and to the left partially obscuring a smaller folder icon with a plus sign Что-то нужно скопировать.
move plus sign made of two thin lines. The four points are small arrows facing out Что-то нужно переместить.
no-drop pointer icon and a not allowed icon Элемент не может быть уронен в текущем местоположении.
ошибка 275173 : в Windows и macOS no-drop на удаление аналогичен запрету на not-allowed .
not-allowed Not allowed icon, which is a circle with a line through it Запрошенные действия не будут осуществлены.
grab fully opened hand icon Что-то можно схватить (перетащить,чтобы переместить).
grabbing closed hand icon, of the back of the hand Что-то схватили (перетащили,чтобы переместить).
Изменение размера и прокрутка all-scroll icon of a medium size dot with four triangles around it. Что-то можно прокрутить в любом направлении (панорамированием).
ошибка 275174 : В Windows, all-scroll — то же самое, что и move .
col-resize col-resize.gif Элемент/столбец может быть изменен по горизонтали.Часто визуализируется как стрелки,указывающие влево и вправо с вертикальной полосой,разделяющей их.
row-resize Элемент/ряд может быть изменен по вертикали.Часто визуализируется как стрелки,указывающие вверх и вниз с горизонтальной полосой,разделяющей их.
n-resize thin long arrow pointing towards the top Некоторый край должен быть перемещен. Например, курсор se-resize используется, когда движение начинается с юго-восточного угла поля.
В некоторых средах отображается эквивалентный двунаправленный курсор изменения размера. Например, n-resize и s-resize такие же, как ns-resize .
e-resize thin long arrow pointing towards the right
s-resize thin long arrow pointing down
w-resize thin long arrow pointing towards the left
ne-resize thin long arrow pointing top-right
nw-resize thin long arrow pointing top-left
se-resize thin long arrow pointing bottom-right
sw-resize thin long arrow pointing  bottom-left
ew-resize thin long arrow pointing left and right Двунаправленный курсор изменения размера.
ns-resize thin long arrow pointing up and down
nesw-resize thin long arrow pointing both to the top-right and bottom-left
nwse-resize thin long arrow pointing both to the top-left and bottom-right
Zooming zoom-in magnifying glass with a plus sign

Что-то можно увеличить (увеличить)или уменьшить.

zoom-out magnifying glass with a minus sign

Formal definition

Formal syntax

cursor =   [ [ <url> | <url-set> ] [ <x> <y> ]? ]#? [ auto | default | none | context-menu | help | pointer | progress | wait | cell | crosshair | text | vertical-text | alias | copy | move | no-drop | not-allowed | grab | grabbing | e-resize | n-resize | ne-resize | nw-resize | s-resize | se-resize | sw-resize | w-resize | ew-resize | ns-resize | nesw-resize | nwse-resize | col-resize | row-resize | all-scroll | zoom-in | zoom-out ]  

Usage notes

Ограничения на размер значков

Хотя спецификация не ограничивает размер изображения cursor пользовательские агенты обычно ограничивают их, чтобы избежать потенциального неправильного использования. Например, в Firefox и Chromium изображения курсора по умолчанию ограничены размером 128×128 пикселей, но рекомендуется ограничить размер изображения курсора до 32×32 пикселей. Изменения курсора с использованием изображений, размер которых превышает максимально поддерживаемый размер пользовательского агента, обычно просто игнорируются.

Поддерживаемые форматы файлов изображений

Спецификация требует от пользовательских агентов поддерживать файлы PNG, файлы SVG v1.1 в безопасном статическом режиме, которые содержат натуральный размер, и любые другие форматы файлов неанимированных изображений, которые они поддерживают для изображений с другими свойствами. Настольные браузеры также широко поддерживают формат файлов .cur .

Спецификация также указывает, что пользовательские агенты должны также поддерживать файлы SVG v1.1 в безопасном анимированном режиме, которые содержат естественный размер, наряду с любыми другими форматами файлов анимированных изображений, которые они поддерживают для изображений в других свойствах. Пользовательские агенты могут поддерживать как статические, так и анимированные изображения SVG, которые не имеют естественного размера.

Other notes

Изменения курсора,пересекающие области панелей инструментов,обычно блокируются во избежание подмены.

Examples

Настройка типов курсора

.foo {
  cursor: crosshair;
}

.bar {
  cursor: zoom-in;
}


.baz {
  cursor: url("hyper.cur"), auto;
}

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox для Android Opera Android Safari на IOS Samsung Internet
cursor

1

12

1

Начиная с Firefox 67,максимальный размер,разрешенный для пользовательских курсоров,составляет 32×32 пикселя в связи с тем,что курсоры неправомерно используются некоторыми вредоносными сайтами.

4

В Internet Explorer 11, когда cursor применяется к элементу, и этот элемент находится под открытым <select> и пользователь наводит курсор на элемент меню <select> , который находится над указанным элементом, курсор для указанного элемента будет отображаться скорее чем обычный курсор <select> . Смотрите ошибку 817822 .

7

1.2

No

18

95

14

1

1.0

alias

1

12

1.5

10

10.6

3

No

18

95

14

1

1.0

all-scroll

1

12

1.5

6

10.6

3

No

18

95

14

1

1.0

auto

1

12

1

4

7

1.2

No

18

95

14

1

1.0

bidirectional_resize

1

12

1.5

10

10.6

3

No

18

95

14

1

1.0

cell

1

12

1.5

10

10.6

3

No

18

95

14

1

1.0

col-resize

1

12

1.5

6

10.6

3

No

18

95

14

1

1.0

context-menu

1

Этот курсор поддерживается только на MacOS и Linux.

12

1.5

Этот курсор поддерживается только на MacOS и Linux.

10

10.6

3

No

18

Этот курсор поддерживается только на MacOS и Linux.

95

14

Этот курсор поддерживается только на MacOS и Linux.

1

1.0

Этот курсор поддерживается только на MacOS и Linux.

copy

1

12

1.5

10

10.6

3

No

18

95

14

1

1.0

crosshair

1

12

1

4

7

1.2

No

18

95

14

1

1.0

default

1

12

1

4

7

1.2

No

18

95

14

1

1.0

grab

68

Chrome также продолжает поддерживать префиксные версии.

1

В Chrome 22 добавлена поддержка Windows.

14

27

1.5

No

55

Opera также продолжает поддерживать версии с префиксами.

15

В Opera 22 добавлена поддержка Windows.

11

4

No

68

Chrome также продолжает поддерживать префиксные версии.

18

В Chrome 22 добавлена поддержка Windows.

95

48

Opera также продолжает поддерживать версии с префиксами.

14

В Opera 22 добавлена поддержка Windows.

1

10.0

1.0

help

1

12

1

4

7

1.2

No

18

95

14

1

1.0

inherit

1

12

1

8

9

1.2

No

18

95

14

1

1.0

move

1

12

1

4

7

1.2

No

18

95

14

1

1.0

no-drop

1

12

1.5

6

10.6

3

No

18

95

14

1

1.0

none

5

12

3

9

15

5

No

18

95

14

4.2

1.0

not-allowed

1

12

1.5

6

10.6

3

No

18

95

14

1

1.0

pointer

1

12

1

6

7

1.2

No

18

95

14

1

1.0

progress

1

12

1

6

7

1.2

No

18

95

14

1

1.0

row-resize

1

12

1.5

6

10.6

3

No

18

95

14

1

1.0

text

1

12

1

4

7

1.2

No

18

95

14

1

1.0

unidirectional_resize

1

12

1

4

7

1.2

No

18

95

14

1

1.0

url

1

12

1.5

Firefox 4 добавил поддержку макросов.

6

15

3

No

18

95

14

1

1.0

url_positioning_syntax

1

79

1.5

Firefox 4 добавил поддержку макросов.

No

15

3

No

18

95

14

1

1.0

vertical-text

1

12

1.5

No

10.6

3

No

18

95

14

1

1.0

wait

1

12

1

4

7

1.2

No

18

95

14

1

1.0

zoom

37

1

12

24

1

No

24

15-23

9

3

No

37

18

95

24

14-24

1

3.0

1.0

See also

  • pointer-events
  • url() function


CSS

  • Пользовательские свойства CSS для каскадных переменных

    CSS Custom Properties for Cascading Variables-это модуль,который позволяет создавать и использовать более и Последнее изменение:17 августа 2022 года,авторский коллектив MDN

  • режимы записи CSS

    CSS Writing Modes-это модуль,определяющий различные международные режимы,такие как «слева направо» (например.

  • <custom-ident>

    Тип данных CSS <custom-ident> обозначает произвольную определяемую пользователем строку, используемую в качестве идентификатора.

  • Descendant combinator

    Комбинатор потомков,обычно представленный одним символом пробела,объединяет два селектора таким образом,что элементы,совпадающие со вторым,выбираются,если они

Свойство cursor устанавливает форму курсора, когда он находится в пределах элемента.

Вид курсора зависит от операционной системы и установленных параметров.

Интерфейс

  • appearance
  • box-sizing
  • caret-color
  • cursor
  • outline
  • outline-width
  • outline-style
  • outline-color
  • outline-offset
  • resize
  • text-overflow
  • user-select

Синтаксис¶

/* Keyword value only */
cursor: pointer;
cursor: auto;

/* Using URL and coordinates */
cursor: url('cursor1.png') 4 12, auto;
cursor: url('cursor2.png') 2 2, pointer;

/* Global values */
cursor: inherit;
cursor: initial;
cursor: unset;

Значения¶

url
Позволяет установить свой собственный курсор, для этого нужно указать путь к файлу с курсором.
auto
Вид курсора по умолчанию для текущего элемента.
none
Отключает отображение курсора.

Остальные допустимые значения приведены в табл. 1.

Табл. 1. Вид курсора

Вид Значение Тест Пример
![default](default.png) default P {cursor: default}
![context-menu](context-menu.png) context-menu P {cursor: context-menu}
![help](help.png) help P {cursor: help}
![pointer](pointer.png) pointer P {cursor: pointer}
![progress](progress.png) progress P {cursor: progress}
![wait](wait.png) wait P {cursor: wait}
![cell](cell.png) cell P {cursor: cell}
![crosshair](crosshair.png) crosshair P {cursor: crosshair}
![text](text.png) text P {cursor: text}
![vertical-text](vertical-text.png) vertical-text P {cursor: vertical-text}
![alias](alias.png) alias P {cursor: alias}
![copy](copy.png) copy P {cursor: copy}
![move](move.png) move P {cursor: move}
![no-drop](no-drop.png) no-drop P {cursor: no-drop}
![not-allowed](not-allowed.png) not-allowed P {cursor: not-allowed}
![all-scroll](all-scroll.png) all-scroll P {cursor: all-scroll}
![col-resize](col-resize.png) col-resize P {cursor: col-resize}
![row-resize](row-resize.png) row-resize P {cursor: row-resize}
![n-resize](n-resize.png) n-resize P {cursor: n-resize}
![ne-resize](ne-resize.png) ne-resize P {cursor: ne-resize}
![e-resize](e-resize.png) e-resize P {cursor: e-resize}
![se-resize](se-resize.png) se-resize P {cursor: se-resize}
![s-resize](s-resize.png) s-resize P {cursor: s-resize}
![sw-resize](sw-resize.png) sw-resize P {cursor: sw-resize}
![w-resize](w-resize.png) w-resize P {cursor: w-resize}
![nw-resize](nw-resize.png) nw-resize P {cursor: nw-resize}
![nesw-resize](nesw-resize.png) nesw-resize P {cursor: nesw-resize}
![nwse-resize](nwse-resize.png) nwse-resize P {cursor: nwse-resize}
![zoom-in](zoom-in.png) zoom-in P {cursor: zoom-in}
![zoom-out](zoom-out.png) zoom-out P {cursor: zoom-out}
![grab](grab.png) grab P {cursor: grab}
![grabbing](grabbing.png) grabbing P {cursor: grabbing}

В зависимости от операционной системы и её настроек вид курсора может отличаться от приведённых в таблице.

При добавлении курсора из файла синтаксис несколько видоизменится.

cursor: url('путь к курсору1'), url('путь к курсору2'), ..., <курсор>

Через запятую допускается указывать несколько значений url, в этом случае браузер попытается открыть первый файл с курсором и если это по каким-либо причинам не получится, перейдёт к следующему файлу. Список обязательно заканчивается ключевым словом, например, auto или pointer, допустимые значения перечислены выше.

Примечание¶

Internet Explorer в качестве формата файла курсора поддерживает CUR и ANI. Firefox, Chrome, Safari поддерживают форматы CUR, PNG, GIF, JPG.

Chrome до версии 36, Opera до версии 24 и Safari до версии 9 поддерживают значения -webkit-zoom-in и -webkit-zoom-out.

Firefox до версии 24 поддерживает значения -moz-zoom-in и -moz-zoom-out.

Chrome до версии 22, Opera до версии 24 и Safari до версии 9 поддерживают значения -webkit-grab и -webkit-grabbing.

Firefox до версии 27 поддерживает значения -moz-grab и -moz-grabbing.

Браузеры на мобильных устройствах не поддерживают свойство cursor.

Значение по-умолчанию:

Применяется ко всем элементам

Спецификации¶

  • CSS Basic User Interface Module Level 3
  • CSS Level 2 (Revision 1)

Поддержка браузерами¶

Can I Use css3-cursors? Data on support for the css3-cursors feature across the major browsers from caniuse.com.

cursor: zoom-in/zoom-out:

Can I Use css3-cursors-newer? Data on support for the css3-cursors-newer feature across the major browsers from caniuse.com.

Примеры¶

Пример 1¶

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>cursor</title>
    <style>
      .cross {
        cursor: crosshair;
      }
      .help {
        cursor: help;
      }
    </style>
  </head>
  <body>
    <p class="cross">
      На этом тексте курсор мыши примет вид перекрестья.
    </p>
    <p>
      <a href="page/help.html" class="help">СПРАВКА 1</a
      ><br />
      <a href="page/help.html" class="help">СПРАВКА 2</a
      ><br />
      <a href="page/help.html" class="help">СПРАВКА 3</a>
    </p>
  </body>
</html>

Пример 2¶

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>cursor</title>
    <style>
      a {
        cursor: url('cursor/sniper.cur'), pointer;
      }
    </style>
  </head>
  <body>
    <p>Обычный текст</p>
    <p>
      <a href="page/1.html">Ссылка 1</a>
      <a href="page/2.html">Ссылка 2</a>
      <a href="page/3.html">Ссылка 3</a>
    </p>
  </body>
</html>

Ссылки¶

  • Свойство cursor на сайте MDN

Понравилась статья? Поделить с друзьями:
  • Current thread is not owner java как исправить
  • Current running mode как исправить
  • Cx freeze python error in main script ansys
  • Current pending sectors victoria как исправить
  • Current pending errors count как исправить hddscan