Фокус стиля

The focus indicator, often signified by a "focus ring," identifies the element in focus on your page. For users who can't or don't want to use a mouse, this indicator is extremely important , because it acts as a stand-in for a mouse-pointer.

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

Используйте :focus , чтобы всегда отображать индикатор фокуса.

Псевдокласс :focus применяется к элементам, находящимся в фокусе, независимо от используемого метода ввода или устройства (например, мыши, клавиатуры или стилуса).

Например, следующий <div> имеет tabindex , который делает его фокусируемым, с пользовательским стилем для его состояния :focus :

div[tabindex="0"]:focus {
  outline: 4px dashed orange;
}

Независимо от того, какое устройство вы используете, <div> выглядит одинаково в фокусе.

К сожалению, браузеры могут по-разному распределять фокус. То, получает ли элемент фокус, зависит от браузера и операционной системы.

Например, следующая <button> имеет пользовательский CSS для своего состояния :focus .

button:focus {
  outline: 4px dashed orange;
}

If you click the <button> with a mouse in Chrome on macOS you should see its custom focus style. However, you won't see the custom focus style if you click the <button> in Safari on macOS. This is because in Safari the element does not receive focus when you click it.

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

Используйте :focus-visible для выборочного отображения индикатора фокуса.

The :focus-visible pseudo-class is applied when an element receives focus and the browser determines (with heuristics) that displaying a focus indicator would be beneficial to the user. In particular, if the most recent user interaction was with a keyboard and the key press did not include a meta, ALT , OPTION , or CONTROL key, then :focus-visible will match.

Кнопка в следующем примере выборочно отображает индикатор фокуса. Если щелкнуть мышью, результат будет иным, чем если сначала нажать на неё с помощью клавиатуры.

button:focus-visible {
  outline: 4px dashed orange;
}

Используйте :focus-within для стилизации родительского элемента, находящегося в фокусе.

The :focus-within pseudo-class is applied to an element when the element itself receives focus or when a child element receives focus. It can be used to highlight a region of the page to draw the user's attention to that area.

Например, форма получает фокус как при выборе самой формы, так и при выборе любого из ее переключателей.

form:focus-within {
  background: #ffecb3;
}

Когда отображать индикатор фокусировки

Хороший вопрос — задать себе: «Если вы нажмете на этот элемент управления, используя мобильное устройство, ожидаете ли вы, что на нем отобразится клавиатура?»

  • If yes : The control should always show a focus indicator, regardless of the input device. For example, this is almost always true of the <input type="text"> element. The user needs to send input to the element with the keyboard, regardless of how the input element becomes in focus.
  • Если нет : элемент управления может выборочно отображать индикатор фокуса. Например, когда пользователь нажимает кнопку <button> мышью или на сенсорном экране, действие завершается. Индикатор фокуса может быть не нужен. Однако, если пользователь использует клавиатуру, отображение индикатора фокуса может быть полезным, чтобы пользователь мог решить, активировать ли элемент управления клавишами ENTER или SPACE .

Избегайте outline: none

The way browsers decide when to draw a focus indicator is, frankly, very confusing. Changing the appearance of a <button> element with CSS or giving an element a tabindex causes the browser's default focus ring behavior to kick-in.

Иногда разработчики удаляют индикатор фокуса с помощью CSS:

/* Don't do this!!! */
:focus {
  outline: none;
}

A better way to work around this issue is to combine :focus and the :focus-visible polyfill. The first block of code demonstrates how the polyfill works, and the sample app beneath it provides an example of using the polyfill to change the focus indicator on a button.

/*
  This hides the focus indicator if the element receives focus with a
  mouse, but it still shows up on keyboard focus.
*/
.js-focus-visible :focus:not(.focus-visible) {
  outline: none;
}

/*
  Optionally: Define a strong focus indicator for keyboard focus.
  If you choose to skip this step, then the browser's default focus
  indicator will be displayed instead.
*/
.js-focus-visible .focus-visible {
  ...
}