Role attribute with multiple values
In what cases may be necessary to set multiple values for a role attribute, and how browsers and screen readers deal with this.
diff --git a/assets/ico-language.svg b/assets/ico-language.svg
index 408145f..3a6678c 100644
--- a/assets/ico-language.svg
+++ b/assets/ico-language.svg
@@ -2,4 +2,4 @@
Most likely, such a page does not exist.
Most likely, such a page does not exist.
Recently, I discovered by chance that the role
attribute may contain more than one value. This was very unexpected, at least for me.
So, I wrote this post out of research interest, so it doesn't contain much practical advice. In fact, some of it's better not put into practice.
Roles contain information on functions of elments, and how it can be interacted with. For example, screen readers will announce that the button
element has the button
role which means that this element is clicable.
Elements can have either implicit or explicit roles. The latter are specified in the role
attribute.
There are many categories of roles, each with clear rules for their explicit usage. For instance, you can't change roles during interaction with an element, or set abstract roles, such as landmark
, section
, widget
, etc. There are also roles that assume nested elements. For example, an element with role="menu"
must have at least one menuitem
element nested within it. However, the main rule is to set roles explicitly as rarely as possible, especially to avoid overriding semantics of elements.
In WAI-ARIA (Web Accessibility Initiative - Accessible Rich Internet Applications), as the most obvious source about roles, there are no examples with two values for the attribute. I had to look up information about the multiple values in this case.
Clause 7.1 Role Attribute in WAI-ARIA 1.1 contains the characteristics of the role
attribute that should be considered in a host languages:
- The attribute name MUST be
role
;- The attribute value MUST allow a token list as the value;
- The appearance of the name literal of any concrete WAI-ARIA role as one of these tokens MUST NOT in and of itself make the attribute value illegal in the host-language syntax; and
- The first name literal of a non-abstract WAI-ARIA role in the list of tokens in the role attribute defines the role according to which the user agent MUST process the element. User Agent processing for roles is defined in the Core Accessibility API Mappings 1.1.
Clauses 8.1 Role Attribute of WAI-ARIA versions 1.2 and 1.3 provides almost the same description:
- The attribute value MUST allow a token list as the value;
- The appearance of the name literal of any concrete WAI-ARIA role as one of these tokens MUST NOT in and of itself make the attribute value illegal in the host-language syntax; and
- The first name literal of a non-abstract WAI-ARIA role in the list of tokens in the role attribute defines the role according to which the user agent MUST process the element. User Agent processing for roles is defined in the Core Accessibility API Mappings 1.2.
Since all versions of WAI-ARIA refers to other documentation, let is read it now.
Core Accessibility API Mappings (Core-AAM for short) is a specification for browsers and other user agents. It describes how they must interact with Accessibility API.
Clause 5.4 Role mapping of Core-AAM 1.1 says what we want to find out:
Traditionally Accessibility API platforms have a limited set of predefined roles that are expected by assistive technologies on that platform, and only one or two roles can be provided. In contrast, WAI-ARIA allows multiple roles to be specified as an ordered set of valid role tokens separated by spaces. Additional roles are fallback for other roles, which is similar to the concept of specifying multiple fonts in case the first font type isn't supported.
This part of the document collects rules for roles themselves.
- The user agent MUST use the first token in the sequence of tokens in the role attribute value which matches the name of any non-abstract WAI-ARIA role according to rules that are specified in the Role Mapping Table below. Note that when WAI-ARIA roles override host language semantics, there are no changes in the DOM, only in the accessibility tree.
- User agents MUST NOT map roles defined in the WAI-ARIA specification as "abstract" via the standard role mechanism of the accessibility API.
In Core-AAM 1.2 you find almost the same information, but also more details about roles supporting by different Accessibility APIs.
A long time ago in HTML standard there was Clause 3.2.7.3.1 ARIA Role Attribute. It described the ability to add multiple roles for one element:
Every HTML element may have an ARIA role attribute specified. This is an ARIA Role attribute as defined by ARIA Section 5.4 Definition of Roles.
The attribute, if specified, must have a value that is a set of space-separated tokens representing the various WAI-ARIA roles that the element belongs to.
The WAI-ARIA role that an HTML element has assigned to it is the first non-abstract role found in the list of values generated when the role attribute is split on spaces.
This clause doesn't exist anymore, but the Internet never forgets.
What conclusions can be drawn after exploring the specifications?
role
Now we are going to check what browsers and screen readers will do with two values for role
. We will experiment in Chrome 97, Firefox 96, and Safari 14 with NVDA 2021.2 and desktop version of VoiceOver.
By the way, in old browsers and screen readers, this cannot be tested. They simply ignore role=""
with multiple values. Keep this in mind.
The markup I will be testing might be scary. This is a test of the single attribute, so I decided to use forbidden techniques at least once in my life 😀. In real projects, it's better never to do this. This is a terrible anti-pattern (and can be consider as a crime, ha-ha.)
<div
+ } Role attribute with multiple values
- ARIA
- HTML
Updated: Recently, I discovered by chance that the role
attribute may contain more than one value. This was very unexpected, at least for me.
So, I wrote this post out of research interest, so it doesn't contain much practical advice. In fact, some of it's better not put into practice.
Background on roles
Roles contain information on functions of elments, and how it can be interacted with. For example, screen readers will announce that the button
element has the button
role which means that this element is clicable.
Elements can have either implicit or explicit roles. The latter are specified in the role
attribute.
There are many categories of roles, each with clear rules for their explicit usage. For instance, you can't change roles during interaction with an element, or set abstract roles, such as landmark
, section
, widget
, etc. There are also roles that assume nested elements. For example, an element with role="menu"
must have at least one menuitem
element nested within it. However, the main rule is to set roles explicitly as rarely as possible, especially to avoid overriding semantics of elements.
What standards and specifications say?
In WAI-ARIA (Web Accessibility Initiative - Accessible Rich Internet Applications), as the most obvious source about roles, there are no examples with two values for the attribute. I had to look up information about the multiple values in this case.
WAI-ARIA
Clause 7.1 Role Attribute in WAI-ARIA 1.1 contains the characteristics of the role
attribute that should be considered in a host languages:
- The attribute name MUST be
role
; - The attribute value MUST allow a token list as the value;
- The appearance of the name literal of any concrete WAI-ARIA role as one of these tokens MUST NOT in and of itself make the attribute value illegal in the host-language syntax; and
- The first name literal of a non-abstract WAI-ARIA role in the list of tokens in the role attribute defines the role according to which the user agent MUST process the element. User Agent processing for roles is defined in the Core Accessibility API Mappings 1.1.
Clauses 8.1 Role Attribute of WAI-ARIA versions 1.2 and 1.3 provides almost the same description:
- The attribute value MUST allow a token list as the value;
- The appearance of the name literal of any concrete WAI-ARIA role as one of these tokens MUST NOT in and of itself make the attribute value illegal in the host-language syntax; and
- The first name literal of a non-abstract WAI-ARIA role in the list of tokens in the role attribute defines the role according to which the user agent MUST process the element. User Agent processing for roles is defined in the Core Accessibility API Mappings 1.2.
Since all versions of WAI-ARIA refers to other documentation, let is read it now.
Core Accessibility API Mappings
Core Accessibility API Mappings (Core-AAM for short) is a specification for browsers and other user agents. It describes how they must interact with Accessibility API.
Clause 5.4 Role mapping of Core-AAM 1.1 says what we want to find out:
Traditionally Accessibility API platforms have a limited set of predefined roles that are expected by assistive technologies on that platform, and only one or two roles can be provided. In contrast, WAI-ARIA allows multiple roles to be specified as an ordered set of valid role tokens separated by spaces. Additional roles are fallback for other roles, which is similar to the concept of specifying multiple fonts in case the first font type isn't supported.
This part of the document collects rules for roles themselves.
- The user agent MUST use the first token in the sequence of tokens in the role attribute value which matches the name of any non-abstract WAI-ARIA role according to rules that are specified in the Role Mapping Table below. Note that when WAI-ARIA roles override host language semantics, there are no changes in the DOM, only in the accessibility tree.
- User agents MUST NOT map roles defined in the WAI-ARIA specification as "abstract" via the standard role mechanism of the accessibility API.
In Core-AAM 1.2 you find almost the same information, but also more details about roles supporting by different Accessibility APIs.
HTML standard
A long time ago in HTML standard there was Clause 3.2.7.3.1 ARIA Role Attribute. It described the ability to add multiple roles for one element:
Every HTML element may have an ARIA role attribute specified. This is an ARIA Role attribute as defined by ARIA Section 5.4 Definition of Roles.
The attribute, if specified, must have a value that is a set of space-separated tokens representing the various WAI-ARIA roles that the element belongs to.
The WAI-ARIA role that an HTML element has assigned to it is the first non-abstract role found in the list of values generated when the role attribute is split on spaces.
This clause doesn't exist anymore, but the Internet never forgets.
Put it simple
What conclusions can be drawn after exploring the specifications?
- Multiple values can be specified for
role
- Multiple values are listed with spaces between them
- Multiple roles are needed for fallback. If the first role isn't supported or doesn't exist, the second one is applied, and so on
- If it is an abstract role, browsers and screen readers will ignore it.
Let is testing
Now we are going to check what browsers and screen readers will do with two values for role
. We will experiment in Chrome 97, Firefox 96, and Safari 14 with NVDA 2021.2 and desktop version of VoiceOver.
By the way, in old browsers and screen readers, this cannot be tested. They simply ignore role=""
with multiple values. Keep this in mind.
The markup I will be testing might be scary. This is a test of the single attribute, so I decided to use forbidden techniques at least once in my life 😀. In real projects, it's better never to do this. This is a terrible anti-pattern (and can be consider as a crime, ha-ha.)
Two valid values
<div
role="button link"
aria-label="This is not a button"
tabindex="1"
diff --git a/en/articles/aria-live-regions/index.html b/en/articles/aria-live-regions/index.html
index b61d52d..c8b8589 100644
--- a/en/articles/aria-live-regions/index.html
+++ b/en/articles/aria-live-regions/index.html
@@ -21,7 +21,7 @@
},
"datePublished": "2024-05-11T00:00:00.000Z",
"dateModified": "2024-09-02T00:00:00.000Z"
- } What you need to know about ARIA live regions
- ARIA
- HTML
- Screen readers
Updated: (This is a translation of my Russian-language article from Web Standards edited by Vadim Makeev and Olga Aleksashenko. I've also rewritten some parts and provided more details based on ″What Live Regions are?″ on Doka Guide).
If you have a dynamically changing part of a page and you're thinking about making it accessible, you may wonder how to do it. This could apply to:
- Chats
- Progress bars and timers
- News and weather widgets
- Alerts and notifications (new messages, likes, subscriptions)
- Currency rates and tickers (stock quotes, indices, bonds)
- Sports statistics, and more.
Previously, assistive technologies (particularly screen readers) couldn't properly process these dynamic elements. Users wouldn't know about errors or new data until they returned to a previous section or reached the end of the page. Now the accessibility of dynamically changing content can be addressed using ARIA.
If you're unfamiliar with this acronym, WAI-ARIA or simply ARIA (Web Accessibility Initiative - Accessible Rich Internet Applications) is a standard consisting of special roles and attributes added to markup. These roles and attributes extend or augment the functionality of standard HTML elements or elements in another programming host languages.
To create a dynamic (″alive″) part of the page where changes occur, we need to implement what ARIA terminology calls a ″Live Region″. The WAI-ARIA 1.2 standard defines a live region as follows:
Live Regions are perceived areas of pages that are usually updated as a result of an external event when a user focuses somewhere else. These regions are not always updated due to user interaction with an UI. This practice has become commonplace as a result of the heavy use of Ajax.
Thus, by using live regions, we can ensure that users of screen readers are informed about important changes on the page, even when they set keyboard focus on a different element.
First of all, we need to create changes on a page. Basically, it's all about manipulating HTML elements and their content. For that, you can do these:
- Add or delete a content as the page loads or after it's refreshed
- Add or delete an element to the page using JavaScript
- Change or add only the content of an element while keeping the element itself on the page
- Change the value of the
display
CSS property from none
to block
, or visibility
from hidden
to visible
- Add or remove the
hidden
HTML attribute from an element.
The second step is all about creating a live region where any of the changes from the previous list happen. For this purpose, we have two options: Use native HTML elements and a set of special ARIA roles and attributes. Once implemented, changes to all child elements within the live region will become accessible to screen readers.
HTML elements
Unfortunately, there are not many native HTML elements for live regions (at least for now). One of them is the <output>
element.
<output>
used to display results. These could be mathematical calculations or the correct missing word in a sentence for grammar tests. Another less obvious use case is for pop-up notifications or toasts 🧇. These are alerts that slide in at the bottom or top of the screen and disappear after some time.
<button>Save</button>
+ } What you need to know about ARIA live regions
- ARIA
- HTML
- Screen readers
Updated: (This is a translation of my Russian-language article from Web Standards edited by Vadim Makeev and Olga Aleksashenko. I've also rewritten some parts and provided more details based on ″What Live Regions are?″ on Doka Guide).
If you have a dynamically changing part of a page and you're thinking about making it accessible, you may wonder how to do it. This could apply to:
- Chats
- Progress bars and timers
- News and weather widgets
- Alerts and notifications (new messages, likes, subscriptions)
- Currency rates and tickers (stock quotes, indices, bonds)
- Sports statistics, and more.
Previously, assistive technologies (particularly screen readers) couldn't properly process these dynamic elements. Users wouldn't know about errors or new data until they returned to a previous section or reached the end of the page. Now the accessibility of dynamically changing content can be addressed using ARIA.
If you're unfamiliar with this acronym, WAI-ARIA or simply ARIA (Web Accessibility Initiative - Accessible Rich Internet Applications) is a standard consisting of special roles and attributes added to markup. These roles and attributes extend or augment the functionality of standard HTML elements or elements in another programming host languages.
To create a dynamic (″alive″) part of the page where changes occur, we need to implement what ARIA terminology calls a ″Live Region″. The WAI-ARIA 1.2 standard defines a live region as follows:
Live Regions are perceived areas of pages that are usually updated as a result of an external event when a user focuses somewhere else. These regions are not always updated due to user interaction with an UI. This practice has become commonplace as a result of the heavy use of Ajax.
Thus, by using live regions, we can ensure that users of screen readers are informed about important changes on the page, even when they set keyboard focus on a different element.
First of all, we need to create changes on a page. Basically, it's all about manipulating HTML elements and their content. For that, you can do these:
- Add or delete a content as the page loads or after it's refreshed
- Add or delete an element to the page using JavaScript
- Change or add only the content of an element while keeping the element itself on the page
- Change the value of the
display
CSS property from none
to block
, or visibility
from hidden
to visible
- Add or remove the
hidden
HTML attribute from an element.
The second step is all about creating a live region where any of the changes from the previous list happen. For this purpose, we have two options: Use native HTML elements and a set of special ARIA roles and attributes. Once implemented, changes to all child elements within the live region will become accessible to screen readers.
HTML elements
Unfortunately, there are not many native HTML elements for live regions (at least for now). One of them is the <output>
element.
<output>
used to display results. These could be mathematical calculations or the correct missing word in a sentence for grammar tests. Another less obvious use case is for pop-up notifications or toasts 🧇. These are alerts that slide in at the bottom or top of the screen and disappear after some time.
<button>Save</button>
<div>
<output>
diff --git a/en/articles/css-media-features-for-a11y/index.html b/en/articles/css-media-features-for-a11y/index.html
index 208d22f..29700c6 100644
--- a/en/articles/css-media-features-for-a11y/index.html
+++ b/en/articles/css-media-features-for-a11y/index.html
@@ -21,7 +21,7 @@
},
"datePublished": "2024-05-09T00:00:00.000Z",
"dateModified": "2024-09-05T00:00:00.000Z"
- } CSS media features to improve accessibility
- CSS
- Usability
Updated: When people talk about accessibility and CSS, they often mean properties that affect the accessibility tree and assistive technologies such as screen readers and voice control software. But there's another ally in the battle for accessible interfaces — media features.
Media features are conditions for the @media
CSS at-rule. They indicate specific characteristics of the device or browser. For example, screen orientation (orientation
) or display mode (display-mode
).
In this article, I'll talk about a few media features: prefers-reduced-motion
, prefers-color-scheme
, inverted-colors
, forced-colors
, ms-high-contrast
, prefers-contrast
, and prefers-reduced-transparency
.
These media features track operating system settings which changed by users who aren't satisfied with the default behavior of the system. For example, people with disabilities and those who are uncomfortable with the default design. Real world examples:
- Users prone to epileptic seizures turn off animation because it can trigger a photosensitive seizures
- Some people with astigmatism choose a dark theme and reduce contrast to avoid eye strain.
Considering user preferences will make the site's interface more flexible and personalized. This will not only help improve its accessibility but can also increase conversion rates. It's always nice to use products that cares about your preferences.
Most customizations apply only to the operating system. Many of them, like animations and contrast levels, don't change website interfaces. It all depends on whether the developers have taken them into account. This is where media features come in handy.
You can also track user settings with JavaScript, but I don't want to make this post bigger. I'll just focus on CSS features.
System settings
Let's take a look at the settings which can be considered in web interfaces now or in the future.
Animation
Animation settings allow you to change the speed of animations or turn them off completely. These settings don't affect websites unless they contain specific CSS at-rule styles.
Users who may adjust animation settings include:
- People with vestibular disorders or those prone to seizures
- People with cognitive disabilities and neurodivergent users, particularly those with attention deficit disorder (ADD).
Most operating systems include the ″Reduce motion″ or ″Minimize animation″ setting to accommodate these users needs.
Color scheme
Users can also change the color scheme settings and select the colors that will dominate the system. These are either light or dark shades. The setting does not affect sites if they do not support color schemes.
The following categories of users utilize color scheme setting:
- People with visual impairments. For example, a person with low vision, eye strain, and light sensitivity
- Those with cognitive disabilities and neurodivergent folks. For instance, individuals with ADD
- Everyone else due to aesthetic preferences, habits, or lighting conditions.
Color schemes can be selected in all popular operating systems. macOS and iOS have an additional automatic theme. If selected, it applies a light theme during the day and a dark theme at night.
Inverted colors
Inverted colors mode replaces system colors with their opposites, like a negative. It's a part of the filtered display mode category of settings.
Colors change not only in the system but also in browser tabs. So users might choose this mode instead of a dark theme. The screenshot shows how the inversion mode works. Yellow shades have turned blue, green has become magenta, and white has turned black.
Who uses inverted colors mode:
- People with visual impairments. For example, individuals with glaucoma or eye strain
- People with migraines and headaches
- Other users due to personal preferences, habits, or lighting conditions.
Most operating systems have inverted colors setting. On iOS, there are even two types of inversion: Smart and classic. In smart invert mode, pictures and videos are not inverted, while in classic one, all content is inverted.
Forced colors
Forced colors mode limits the number of colors to improve text readability by changing the contrast between text and background. High-contrast colors are mainly used. This mode changes colors both in the system and on websites.
Who uses forced colors mode:
- Users with visual impairments
- People with migraines and headaches
- People with photosensitive epilepsy
- Users who need to reduce visual noise to improve concentration.
Currently, this mode can only be selected on Windows. On Windows 10 and earlier versions, it's called Windows high contrast mode (WHCM). On Windows 11, it's called contrast themes.
The high contrast mode has several pre-set color schemes:
- High contrast black
- High contrast white
- High contrast one (1) and two (2).
The technology for replacing the color palette depends on the browser. It differs in Chromium-based browsers, Firefox (Quantum engine), Internet Explorer (Trident), and in older versions of Edge (EdgeHTML). For example, in Vivaldi (Chromium), the white background of the site becomes black, gray links and borders become bright yellow, and regular text becomes white instead of dark gray.
In Firefox, the originally white background will remain the same, gray links and borders will become bright blue, and regular text will be black instead of dark gray.
You can change the default behavior in Firefox. The setting is located in the Language and Appearance section, specifically in the ″Colors″ subsection. Open the modal window with the ″Manage Colors…″ button and select the ″Use system colors″ checkbox.
On Windows 11, the set of contrast themes has changed: Aquatic, desert, dusk, and night sky have been added.
If the pre-set themes don't suit you, you can customize them yourself. This includes the option to reduce contrast.
Contrast
Users can separately increase or decrease the level of contrast in the system without changing the screen brightness.
The contrast settings is used by:
- People with visual impairments, for example, those with glaucoma
- People who have migraines and headaches
- Those with old or low-quality displays
- Others who need higher contrast due to lighting conditions.
macOS and iOS have the increased contrast mode. It increases the difference between shades of gray and makes element borders more distinct.
Increasing contrast affects the appearance of both the system and web interfaces. Unlike system windows, only the contrast level changes on websites.
Let's look at what happens to a modal window in macOS with default mode and with increased contrast mode. Both windows show an image of a screaming cat called ″cute-cat.jpeg″. The first window has no frame, and the background of the control panel with buttons and additional settings is light gray. The second window looks visually different from the first. It has a black frame, the background of the control panel has become white, and all buttons and other elements in the panel have separate black frames.
Transparency
Users can enable or disable background transparency. Those who increase contrast often choose an opaque background.
A transparent background can increase cognitive load and reduce text readability. Therefore, this setting is used by:
- People with visual impairments. For example, those with astigmatism or low vision
- Users with cognitive disabilities and neurodivergent people. For instance, dyslexic users or those with ADD
- People with migraines and headaches.
Transparency can be precisely adjusted on Windows and in macOS. These settings not only affect the transparency in the system interface but also on websites and in browsers. This screenshot shows the navigation background of the first window is semi-transparent, while the second one has an opaque and solid background.
A few words about media types
The @media
at-rule in CSS has several media types. They describe the device on which the document is displayed.
all
: All devices. It's set automatically if no other type is specifiedscreen
: Devices with screens. For example, phones and laptopsprint
: Devices with preview and print functions. This includes printersspeech
: Devices with speech synthesis. For example, screen readers and voice assistants.
The speech
media type may be interesting from the point of view of accessibility. However, it is not currently supported by any browser. It used to be supported by the Opera browser on the Presto engine but support ceased after switching to Blink.
In the future, it may be useful for special styles for screen readers, such as to apply CSS properties for speech synthesis devices to some elements on a page.
Media features
Now we move on to media features that will help make web interfaces more accessible.
Some of them are not yet well supported by browsers. Things may change in the future with the development of CSS. In any case, it's useful to know about them.
prefers-reduced-motion
It tracks whether animation settings are selected to reduce its intensity. This is useful for any animation on the website. The animation can be slowed down or completely disabled.
Values for prefers-reduced-motion
:
no-preference
: Default animation settingsreduce
: Modified animation settings.
Browser support for prefers-reduced-motion
is relatively good: 97% (as of 2024).
In this code example we stop animation completely by using animation: none
.
@media (prefers-reduced-motion: reduce) {
+ } CSS media features to improve accessibility
- CSS
- Usability
Updated: When people talk about accessibility and CSS, they often mean properties that affect the accessibility tree and assistive technologies such as screen readers and voice control software. But there's another ally in the battle for accessible interfaces — media features.
Media features are conditions for the @media
CSS at-rule. They indicate specific characteristics of the device or browser. For example, screen orientation (orientation
) or display mode (display-mode
).
In this article, I'll talk about a few media features: prefers-reduced-motion
, prefers-color-scheme
, inverted-colors
, forced-colors
, ms-high-contrast
, prefers-contrast
, and prefers-reduced-transparency
.
These media features track operating system settings which changed by users who aren't satisfied with the default behavior of the system. For example, people with disabilities and those who are uncomfortable with the default design. Real world examples:
- Users prone to epileptic seizures turn off animation because it can trigger a photosensitive seizures
- Some people with astigmatism choose a dark theme and reduce contrast to avoid eye strain.
Considering user preferences will make the site's interface more flexible and personalized. This will not only help improve its accessibility but can also increase conversion rates. It's always nice to use products that cares about your preferences.
Most customizations apply only to the operating system. Many of them, like animations and contrast levels, don't change website interfaces. It all depends on whether the developers have taken them into account. This is where media features come in handy.
You can also track user settings with JavaScript, but I don't want to make this post bigger. I'll just focus on CSS features.
System settings
Let's take a look at the settings which can be considered in web interfaces now or in the future.
Animation
Animation settings allow you to change the speed of animations or turn them off completely. These settings don't affect websites unless they contain specific CSS at-rule styles.
Users who may adjust animation settings include:
- People with vestibular disorders or those prone to seizures
- People with cognitive disabilities and neurodivergent users, particularly those with attention deficit disorder (ADD).
Most operating systems include the ″Reduce motion″ or ″Minimize animation″ setting to accommodate these users needs.
Color scheme
Users can also change the color scheme settings and select the colors that will dominate the system. These are either light or dark shades. The setting does not affect sites if they do not support color schemes.
The following categories of users utilize color scheme setting:
- People with visual impairments. For example, a person with low vision, eye strain, and light sensitivity
- Those with cognitive disabilities and neurodivergent folks. For instance, individuals with ADD
- Everyone else due to aesthetic preferences, habits, or lighting conditions.
Color schemes can be selected in all popular operating systems. macOS and iOS have an additional automatic theme. If selected, it applies a light theme during the day and a dark theme at night.
Inverted colors
Inverted colors mode replaces system colors with their opposites, like a negative. It's a part of the filtered display mode category of settings.
Colors change not only in the system but also in browser tabs. So users might choose this mode instead of a dark theme. The screenshot shows how the inversion mode works. Yellow shades have turned blue, green has become magenta, and white has turned black.
Who uses inverted colors mode:
- People with visual impairments. For example, individuals with glaucoma or eye strain
- People with migraines and headaches
- Other users due to personal preferences, habits, or lighting conditions.
Most operating systems have inverted colors setting. On iOS, there are even two types of inversion: Smart and classic. In smart invert mode, pictures and videos are not inverted, while in classic one, all content is inverted.
Forced colors
Forced colors mode limits the number of colors to improve text readability by changing the contrast between text and background. High-contrast colors are mainly used. This mode changes colors both in the system and on websites.
Who uses forced colors mode:
- Users with visual impairments
- People with migraines and headaches
- People with photosensitive epilepsy
- Users who need to reduce visual noise to improve concentration.
Currently, this mode can only be selected on Windows. On Windows 10 and earlier versions, it's called Windows high contrast mode (WHCM). On Windows 11, it's called contrast themes.
The high contrast mode has several pre-set color schemes:
- High contrast black
- High contrast white
- High contrast one (1) and two (2).
The technology for replacing the color palette depends on the browser. It differs in Chromium-based browsers, Firefox (Quantum engine), Internet Explorer (Trident), and in older versions of Edge (EdgeHTML). For example, in Vivaldi (Chromium), the white background of the site becomes black, gray links and borders become bright yellow, and regular text becomes white instead of dark gray.
In Firefox, the originally white background will remain the same, gray links and borders will become bright blue, and regular text will be black instead of dark gray.
You can change the default behavior in Firefox. The setting is located in the Language and Appearance section, specifically in the ″Colors″ subsection. Open the modal window with the ″Manage Colors…″ button and select the ″Use system colors″ checkbox.
On Windows 11, the set of contrast themes has changed: Aquatic, desert, dusk, and night sky have been added.
If the pre-set themes don't suit you, you can customize them yourself. This includes the option to reduce contrast.
Contrast
Users can separately increase or decrease the level of contrast in the system without changing the screen brightness.
The contrast settings is used by:
- People with visual impairments, for example, those with glaucoma
- People who have migraines and headaches
- Those with old or low-quality displays
- Others who need higher contrast due to lighting conditions.
macOS and iOS have the increased contrast mode. It increases the difference between shades of gray and makes element borders more distinct.
Increasing contrast affects the appearance of both the system and web interfaces. Unlike system windows, only the contrast level changes on websites.
Let's look at what happens to a modal window in macOS with default mode and with increased contrast mode. Both windows show an image of a screaming cat called ″cute-cat.jpeg″. The first window has no frame, and the background of the control panel with buttons and additional settings is light gray. The second window looks visually different from the first. It has a black frame, the background of the control panel has become white, and all buttons and other elements in the panel have separate black frames.
Transparency
Users can enable or disable background transparency. Those who increase contrast often choose an opaque background.
A transparent background can increase cognitive load and reduce text readability. Therefore, this setting is used by:
- People with visual impairments. For example, those with astigmatism or low vision
- Users with cognitive disabilities and neurodivergent people. For instance, dyslexic users or those with ADD
- People with migraines and headaches.
Transparency can be precisely adjusted on Windows and in macOS. These settings not only affect the transparency in the system interface but also on websites and in browsers. This screenshot shows the navigation background of the first window is semi-transparent, while the second one has an opaque and solid background.
A few words about media types
The @media
at-rule in CSS has several media types. They describe the device on which the document is displayed.
all
: All devices. It's set automatically if no other type is specifiedscreen
: Devices with screens. For example, phones and laptopsprint
: Devices with preview and print functions. This includes printersspeech
: Devices with speech synthesis. For example, screen readers and voice assistants.
The speech
media type may be interesting from the point of view of accessibility. However, it is not currently supported by any browser. It used to be supported by the Opera browser on the Presto engine but support ceased after switching to Blink.
In the future, it may be useful for special styles for screen readers, such as to apply CSS properties for speech synthesis devices to some elements on a page.
Media features
Now we move on to media features that will help make web interfaces more accessible.
Some of them are not yet well supported by browsers. Things may change in the future with the development of CSS. In any case, it's useful to know about them.
prefers-reduced-motion
It tracks whether animation settings are selected to reduce its intensity. This is useful for any animation on the website. The animation can be slowed down or completely disabled.
Values for prefers-reduced-motion
:
no-preference
: Default animation settingsreduce
: Modified animation settings.
Browser support for prefers-reduced-motion
is relatively good: 97% (as of 2024).
In this code example we stop animation completely by using animation: none
.
@media (prefers-reduced-motion: reduce) {
.danger-animation {
animation: none;
}
diff --git a/en/articles/how-to-protect-users-with-epilepsy-and-vd/index.html b/en/articles/how-to-protect-users-with-epilepsy-and-vd/index.html
index 352037e..eb6cb97 100644
--- a/en/articles/how-to-protect-users-with-epilepsy-and-vd/index.html
+++ b/en/articles/how-to-protect-users-with-epilepsy-and-vd/index.html
@@ -21,7 +21,7 @@
},
"datePublished": "2024-05-16T00:00:00.000Z",
"dateModified": "2024-08-26T00:00:00.000Z"
- } Thinking about users with seizures and vestibular conditions
- Design
- Animation
- CSS
Updated: Accessibility helps users not only use interfaces without trouble but also avoid feeling physically unwell. Here, I want to discuss what accessibility means for people with seizures and vestibular conditions.
Vestibular conditions can appear spontaneously. For example, they may occur due to side effects from medications, head injuries, and even hot weather. A similar situation applies to seizures. While we are somewhat prepared for screen reader users, we cannot predict what will make a person feel unwell. Therefore, it's crucial to avoid creating barriers from the start.
Let's start with the definitions of vestibular disorders, seizures, and epilepsy.
Vestibular disorders
It's likely that you have experienced motion sickness, dizziness, or nausea at least once in your life. The reason could be lack of sleep, a cold, a long car journey, or various other factors.
Vestibular disorders are related to the inner ear and the part of the brain that controls balance and eye movement.
This is a large group of medical conditions, including head injuries, vestibular migraine or migraine with aura, and brain tumors. They often have similar symptoms:
- dizziness (vertigo)
- nausea
- blurred vision
- eye strain
- headaches
- trouble concentrating
- confusion.
One of the triggers can be inaccessible user interfaces. Facundo Corradini, in an article on A List Apart, described how he lay in bed for hours with severe vertigo after encountering parallax scrolling effects.
There are indeed many such users. Worldwide, about 15% of people experience migraines (statistics as of 2023).
Seizures and epilepsy
A seizure is uncontrolled increased or synchronized activity of neurons in the brain. Its effects can include dizziness, paralysis, temporary failure of internal organs, loss of consciousness, confusion, partial memory loss, and outbreaks of fear and anxiety.
Seizures can occur on their own or be part of a disability. If they recur frequently, more than three times, they are considered epilepsy. Globally, about 6,5% of people have epilepsy (statistics as of 2019).
Seizures can be influenced not only by internal factors but also by external ones, such as light or sounds. Seizures triggered by light, sounds, and even reading are called reflex seizures. When there are many such seizures, a person has reflex epilepsy (RE).
Reflex epilepsy comes in several types. I am going to focus only on photosensitive epilepsy (PSE). It's triggered by intense flickering light or movement. PSE occurs in 3–5% of all people with epilepsy. The condition manifest between the ages of seven (7) and nineteen (19), but people can experience it in their adult life as well.
Content that flashes, flickers, or blinks can lead to an epileptic seizure. These triggers seriously increase electrical activity in neurons.
Problematic content
Several elements in web interfaces can potentially cause seizures or other adverse physical reactions:
- media content such as videos and GIFs
- animated scrolling that lasts longer than one quarter (1/4) second or 15 milliseconds
- web canvas animations
- graphics with contrasting stripes, squares, spirals, and concentric circles
- SVG, CSS, and JavaScript animations. E.g., moving images next to text or parallax scrolling effects where foreground and background scroll simultaneously in different directions
high contrast elements and interfaces.
I have personally experienced eye strain and nausea due to such visual elements. In my case, it was caused by the splash screen in WebStorm 2021.1, which was just a static image. I'm grateful to the JetBrains team for listening to feedback and reducing the saturation of the images.
For more examples of problematic interfaces, I recommend reading ″Your Interactive Makes Me Sick″ by Eileen Webb. It provides valuable insights into this issue, though I hope your vestibular system handles the challenge better than mine did.
How to protect users?
It's crucial to note that directly involving people with epilepsy and vestibular disorders in testing can be potentially dangerous. Therefore, the most responsible approach is to be proactive and implement expert recommendations.
To ensure we don't unintentionally harm users, consider the guidelines below.
Monitor flash frequency. The rapid appearance of bright light is called flashes. They can be either general or red. Flashes are common in videos and animations.
A general flash is a rapid increase in brightness by 10% or more, followed by a decrease to 0,8% or less.
A red flash is a pair of opposite transitions involving a saturated red color.
Besides flashes, there are also blinks. Blinking content switches between two states. It's usually used to draw attention to specific elements on a page.
The frequency of general and red flashes, as well as blinks, should not exceed three (3) times per second or three (3) hertz (Hz). This is the minimum accessibility requirement for people with photosensitive epilepsy.
The best solution to the problem of flashes and blinks is to avoid them altogether. Another approach is the small safe area technique, where you reduce the size of the video or the part of the page with potentially dangerous animation. The area should occupy less than 10% of the central field of vision or less than 25% of the screen size. This is because the central part of the eye consists of a large number of sensors that more actively transmit signals to the visual cortex and can overload neurons.
Reducing the area of flashes and blinks is not the best solution, as users may access the site from a mobile device and hold it too close to their eyes.
Regarding blinks, if they are short-lived and stop automatically, that's generally acceptable.
You can check videos and animations using the free Photosensitive Epilepsy Analysis Tool (PEAT). However, it's only suitable for non-commercial purposes. For commercial use, there's the paid Harding Test.
Turn off animation. You can disable animation if it's not a key functionality. The prefers-reduced-motion
media feature is useful for this. It checks the ″Reduce Motion″ setting in macOS or the ″Show Animations″ setting in Windows. You can see how this media feature works in W3C demo.
There are no absolute values for speed, smoothness, and other animation properties. So you can rely on the experience of other developers or ask for advice from users.
Option one (1): Only prefers-reduced-motion
(suggested by Val Head).
@media (prefers-reduced-motion: reduce) {
+ } Thinking about users with seizures and vestibular conditions
- Design
- Animation
- CSS
Updated: Accessibility helps users not only use interfaces without trouble but also avoid feeling physically unwell. Here, I want to discuss what accessibility means for people with seizures and vestibular conditions.
Vestibular conditions can appear spontaneously. For example, they may occur due to side effects from medications, head injuries, and even hot weather. A similar situation applies to seizures. While we are somewhat prepared for screen reader users, we cannot predict what will make a person feel unwell. Therefore, it's crucial to avoid creating barriers from the start.
Let's start with the definitions of vestibular disorders, seizures, and epilepsy.
Vestibular disorders
It's likely that you have experienced motion sickness, dizziness, or nausea at least once in your life. The reason could be lack of sleep, a cold, a long car journey, or various other factors.
Vestibular disorders are related to the inner ear and the part of the brain that controls balance and eye movement.
This is a large group of medical conditions, including head injuries, vestibular migraine or migraine with aura, and brain tumors. They often have similar symptoms:
- dizziness (vertigo)
- nausea
- blurred vision
- eye strain
- headaches
- trouble concentrating
- confusion.
One of the triggers can be inaccessible user interfaces. Facundo Corradini, in an article on A List Apart, described how he lay in bed for hours with severe vertigo after encountering parallax scrolling effects.
There are indeed many such users. Worldwide, about 15% of people experience migraines (statistics as of 2023).
Seizures and epilepsy
A seizure is uncontrolled increased or synchronized activity of neurons in the brain. Its effects can include dizziness, paralysis, temporary failure of internal organs, loss of consciousness, confusion, partial memory loss, and outbreaks of fear and anxiety.
Seizures can occur on their own or be part of a disability. If they recur frequently, more than three times, they are considered epilepsy. Globally, about 6,5% of people have epilepsy (statistics as of 2019).
Seizures can be influenced not only by internal factors but also by external ones, such as light or sounds. Seizures triggered by light, sounds, and even reading are called reflex seizures. When there are many such seizures, a person has reflex epilepsy (RE).
Reflex epilepsy comes in several types. I am going to focus only on photosensitive epilepsy (PSE). It's triggered by intense flickering light or movement. PSE occurs in 3–5% of all people with epilepsy. The condition manifest between the ages of seven (7) and nineteen (19), but people can experience it in their adult life as well.
Content that flashes, flickers, or blinks can lead to an epileptic seizure. These triggers seriously increase electrical activity in neurons.
Problematic content
Several elements in web interfaces can potentially cause seizures or other adverse physical reactions:
- media content such as videos and GIFs
- animated scrolling that lasts longer than one quarter (1/4) second or 15 milliseconds
- web canvas animations
- graphics with contrasting stripes, squares, spirals, and concentric circles
- SVG, CSS, and JavaScript animations. E.g., moving images next to text or parallax scrolling effects where foreground and background scroll simultaneously in different directions
high contrast elements and interfaces.
I have personally experienced eye strain and nausea due to such visual elements. In my case, it was caused by the splash screen in WebStorm 2021.1, which was just a static image. I'm grateful to the JetBrains team for listening to feedback and reducing the saturation of the images.
For more examples of problematic interfaces, I recommend reading ″Your Interactive Makes Me Sick″ by Eileen Webb. It provides valuable insights into this issue, though I hope your vestibular system handles the challenge better than mine did.
How to protect users?
It's crucial to note that directly involving people with epilepsy and vestibular disorders in testing can be potentially dangerous. Therefore, the most responsible approach is to be proactive and implement expert recommendations.
To ensure we don't unintentionally harm users, consider the guidelines below.
Monitor flash frequency. The rapid appearance of bright light is called flashes. They can be either general or red. Flashes are common in videos and animations.
A general flash is a rapid increase in brightness by 10% or more, followed by a decrease to 0,8% or less.
A red flash is a pair of opposite transitions involving a saturated red color.
Besides flashes, there are also blinks. Blinking content switches between two states. It's usually used to draw attention to specific elements on a page.
The frequency of general and red flashes, as well as blinks, should not exceed three (3) times per second or three (3) hertz (Hz). This is the minimum accessibility requirement for people with photosensitive epilepsy.
The best solution to the problem of flashes and blinks is to avoid them altogether. Another approach is the small safe area technique, where you reduce the size of the video or the part of the page with potentially dangerous animation. The area should occupy less than 10% of the central field of vision or less than 25% of the screen size. This is because the central part of the eye consists of a large number of sensors that more actively transmit signals to the visual cortex and can overload neurons.
Reducing the area of flashes and blinks is not the best solution, as users may access the site from a mobile device and hold it too close to their eyes.
Regarding blinks, if they are short-lived and stop automatically, that's generally acceptable.
You can check videos and animations using the free Photosensitive Epilepsy Analysis Tool (PEAT). However, it's only suitable for non-commercial purposes. For commercial use, there's the paid Harding Test.
Turn off animation. You can disable animation if it's not a key functionality. The prefers-reduced-motion
media feature is useful for this. It checks the ″Reduce Motion″ setting in macOS or the ″Show Animations″ setting in Windows. You can see how this media feature works in W3C demo.
There are no absolute values for speed, smoothness, and other animation properties. So you can rely on the experience of other developers or ask for advice from users.
Option one (1): Only prefers-reduced-motion
(suggested by Val Head).
@media (prefers-reduced-motion: reduce) {
*:not(.safe-animation),
*:not(.safe-animation)::before,
*:not(.safe-animation)::after {
diff --git a/en/articles/index.html b/en/articles/index.html
index e59f183..4a58748 100644
--- a/en/articles/index.html
+++ b/en/articles/index.html
@@ -1 +1 @@
-All articles — Blog on Digital Accessibility All articles
Role attribute with multiple values
In what cases may be necessary to set multiple values for a role attribute, and how browsers and screen readers deal with this.
Thinking about users with seizures and vestibular conditions
What if the user gets motion sickness because of a website? What if he or she has an epileptic seizure? Let's look at what interfaces for users with seizures and vestibular conditions should look like.
What you need to know about ARIA live regions
If you're looking to make dynamic page content accessible, WAI-ARIA provides a solution. Previously, assistive technologies struggled with these elements, but now they can be properly handled using ARIA live regions.
CSS media features to improve accessibility
Learn how to incorporate user-defined settings into web interfaces. This article explores media features that track various user preferences, including animation, contrast, transparency, inversion, color schemes and forced color modes.
Understanding skip links
How to help users to skip large chank of a page content, whose these users are, and how to implement it on your website.
\ No newline at end of file
+All articles — Blog on Digital Accessibility All articles
Role attribute with multiple values
In what cases may be necessary to set multiple values for a role attribute, and how browsers and screen readers deal with this.
Thinking about users with seizures and vestibular conditions
What if the user gets motion sickness because of a website? What if he or she has an epileptic seizure? Let's look at what interfaces for users with seizures and vestibular conditions should look like.
What you need to know about ARIA live regions
If you're looking to make dynamic page content accessible, WAI-ARIA provides a solution. Previously, assistive technologies struggled with these elements, but now they can be properly handled using ARIA live regions.
CSS media features to improve accessibility
Learn how to incorporate user-defined settings into web interfaces. This article explores media features that track various user preferences, including animation, contrast, transparency, inversion, color schemes and forced color modes.
Understanding skip links
How to help users to skip large chank of a page content, whose these users are, and how to implement it on your website.
\ No newline at end of file
diff --git a/en/articles/understanding-a-skip-link/index.html b/en/articles/understanding-a-skip-link/index.html
index 665395c..0ede532 100644
--- a/en/articles/understanding-a-skip-link/index.html
+++ b/en/articles/understanding-a-skip-link/index.html
@@ -21,7 +21,7 @@
},
"datePublished": "2024-05-05T00:00:00.000Z",
"dateModified": "2024-06-13T00:00:00.000Z"
- } Understanding skip links
- Patterns
- HTML
- CSS
Updated: There are many small but useful patterns available on the web. One of them is a content skip link or skip link. This is a hyperlink that leads to the main content of a page and helps to skip through lengthy, repetitive content. Its main purpose is to save users' time.
What kind of content is considered bulky? A navigation menu with a logo and a lot of links, a complex table, letter indexes, and lists with chapters or technical specifications. Most often, the skip link is useful for skipping site navigation from a header.
Exceptions are a footer menu and a brief header navigation, which consists of a couple of links and a site logo. In the case of footers, you can return to the top of a page using keyboard keys, gestures, and other in-built browser features. So, a brief navigation won't take up much time for users.
In theory, everything is simple. In practice, it's a bit more complicated. Let's learn step by steps.
Theory
What WCAG 2.2 says
In the accessibility guidelines, there are two criteria related to skip links.
- Criterion 2.1.1 Keyboard (A). All functionality of the content is operable through a keyboard interface without requiring specific timings for individual keystrokes.
- Criterion 2.4.1 Block Skipping (A). A mechanism is available to bypass blocks of content that are repeated on multiple web pages.
Mechanics for skipping blocks
There are two mechanics for skipping content on a web page:
- Landmark navigation (landmarks)
- Skip link.
The first method is available for screen reader users. Landmarks are created using semantic tags, thanks to ARIA. The second mechanic has a larger audience. It's not only for users with visual impairments.
You can find advice that the skip link isn't necessary for websites with a good layouts. This isn't quite true. Not all screen reader users know about shortcuts for landmarks. Other keyboard users don't have this option at all. Also, the more options for navigation, the better.
Who needs it
In short, anyone who consistently navigates through pages and can't skip content quickly. In a nutshell, there are four (4) categories of users.
- Screen reader users, who navigate through websites with a keyboard and mobile versions of websites by taps and swipes
- Users with motor impairments who use a keyboard, remote computer buttons, and other switch devices
- Any other keyboard users. They may be of an advanced level or have temporarily broken devices, such as a computer mouse, etc.
- Screen magnifier users who use the keyboard to navigate.
Imagine that you're using a keyboard for navigation and open any online shopping platform. You found the product you wanted, navigated to it, and found yourself on the top of the page. About forty (40) tabs later, you can finally find out more about your perfect backpack. With the skip link, you would be in the right part of a page in one tab and not fall asleep on the way 😴.
List of requirements
- Located in tab order first
- Leads directly to the main content and sets the focus on it. It's more effective if the page has one main area
- It can be located in the main part of the page. In this case, it skips the necessary block and leads to the beginning of the next part of a web page
- It has a clear name and a good description of where it leads
- It can always be visible, or it can appear when a person uses a keyboard. In both cases, it meets WCAG criteria
- You can add more than one of the skip links. For example, one leads to the main content, and the second to the search bar. It's better don't overdo the number. Otherwise, there is no point in the skip-link pattern
- It shouldn't interfere with mouse users. This is a controversial requirement, but it has a grain of truth. If such a link is always visible, it may confuse mouse users. They aren't familiar with this pattern, and don't need another way to scroll to the main content.
Practice
You need to support keyboard navigation from the start. In other cases, the skip link is useless by default.
Marking up the page
Before we move on to HTML and CSS, I want to say a couple of words about skip link names. On English-language websites, ″Skip to main content″ or ″Skip to content″ is most often used. There are a few more options:
- Skip navigation
- Skip main navigation
- Skip navigation links.
Finally, let's talk about HTML.
The practical implementation of the skip link is an anchor link. It's better to add it at start of a page, before other HTML elements. The best parts of HTML code for that reason are <header>
if it's the first element on the page or <body>
. I'm going to use the link as the first child element for the header one.
<header>
+ } Understanding skip links
- Patterns
- HTML
- CSS
Updated: There are many small but useful patterns available on the web. One of them is a content skip link or skip link. This is a hyperlink that leads to the main content of a page and helps to skip through lengthy, repetitive content. Its main purpose is to save users' time.
What kind of content is considered bulky? A navigation menu with a logo and a lot of links, a complex table, letter indexes, and lists with chapters or technical specifications. Most often, the skip link is useful for skipping site navigation from a header.
Exceptions are a footer menu and a brief header navigation, which consists of a couple of links and a site logo. In the case of footers, you can return to the top of a page using keyboard keys, gestures, and other in-built browser features. So, a brief navigation won't take up much time for users.
In theory, everything is simple. In practice, it's a bit more complicated. Let's learn step by steps.
Theory
What WCAG 2.2 says
In the accessibility guidelines, there are two criteria related to skip links.
- Criterion 2.1.1 Keyboard (A). All functionality of the content is operable through a keyboard interface without requiring specific timings for individual keystrokes.
- Criterion 2.4.1 Block Skipping (A). A mechanism is available to bypass blocks of content that are repeated on multiple web pages.
Mechanics for skipping blocks
There are two mechanics for skipping content on a web page:
- Landmark navigation (landmarks)
- Skip link.
The first method is available for screen reader users. Landmarks are created using semantic tags, thanks to ARIA. The second mechanic has a larger audience. It's not only for users with visual impairments.
You can find advice that the skip link isn't necessary for websites with a good layouts. This isn't quite true. Not all screen reader users know about shortcuts for landmarks. Other keyboard users don't have this option at all. Also, the more options for navigation, the better.
Who needs it
In short, anyone who consistently navigates through pages and can't skip content quickly. In a nutshell, there are four (4) categories of users.
- Screen reader users, who navigate through websites with a keyboard and mobile versions of websites by taps and swipes
- Users with motor impairments who use a keyboard, remote computer buttons, and other switch devices
- Any other keyboard users. They may be of an advanced level or have temporarily broken devices, such as a computer mouse, etc.
- Screen magnifier users who use the keyboard to navigate.
Imagine that you're using a keyboard for navigation and open any online shopping platform. You found the product you wanted, navigated to it, and found yourself on the top of the page. About forty (40) tabs later, you can finally find out more about your perfect backpack. With the skip link, you would be in the right part of a page in one tab and not fall asleep on the way 😴.
List of requirements
- Located in tab order first
- Leads directly to the main content and sets the focus on it. It's more effective if the page has one main area
- It can be located in the main part of the page. In this case, it skips the necessary block and leads to the beginning of the next part of a web page
- It has a clear name and a good description of where it leads
- It can always be visible, or it can appear when a person uses a keyboard. In both cases, it meets WCAG criteria
- You can add more than one of the skip links. For example, one leads to the main content, and the second to the search bar. It's better don't overdo the number. Otherwise, there is no point in the skip-link pattern
- It shouldn't interfere with mouse users. This is a controversial requirement, but it has a grain of truth. If such a link is always visible, it may confuse mouse users. They aren't familiar with this pattern, and don't need another way to scroll to the main content.
Practice
You need to support keyboard navigation from the start. In other cases, the skip link is useless by default.
Marking up the page
Before we move on to HTML and CSS, I want to say a couple of words about skip link names. On English-language websites, ″Skip to main content″ or ″Skip to content″ is most often used. There are a few more options:
- Skip navigation
- Skip main navigation
- Skip navigation links.
Finally, let's talk about HTML.
The practical implementation of the skip link is an anchor link. It's better to add it at start of a page, before other HTML elements. The best parts of HTML code for that reason are <header>
if it's the first element on the page or <body>
. I'm going to use the link as the first child element for the header one.
<header>
<a href="#main-content" class="skip-link">
Skip to content
</a>
diff --git a/en/feed.xml b/en/feed.xml
index d9a8c0e..a6572a3 100644
--- a/en/feed.xml
+++ b/en/feed.xml
@@ -1 +1 @@
-Blog on Digital Accessibility Practical advice on digital accessibility for frontend developers, QA testers and designers. Here you'll learn about methods of creating accessible and user-friendly interfaces, standards, assistive technologies and laws. https://a11y-blog.dev/Mon, 03 Jun 2024 00:00:00 GMT Role attribute with multiple values In what cases may be necessary to set multiple values for a role attribute, and how browsers and screen readers deal with this. https://a11y-blog.dev/en/articles/aria-attribute-role-with-multiple-values/Mon, 03 Jun 2024 00:00:00 GMT https://a11y-blog.dev/en/articles/aria-attribute-role-with-multiple-values/ Thinking about users with seizures and vestibular conditions What if the user gets motion sickness because of a website? What if he or she has an epileptic seizure? Let's look at what interfaces for users with seizures and vestibular conditions should look like. https://a11y-blog.dev/en/articles/how-to-protect-users-with-epilepsy-and-vd/Thu, 16 May 2024 00:00:00 GMT https://a11y-blog.dev/en/articles/how-to-protect-users-with-epilepsy-and-vd/ What you need to know about ARIA live regions If you're looking to make dynamic page content accessible, WAI-ARIA provides a solution. Previously, assistive technologies struggled with these elements, but now they can be properly handled using ARIA live regions. https://a11y-blog.dev/en/articles/aria-live-regions/Sat, 11 May 2024 00:00:00 GMT https://a11y-blog.dev/en/articles/aria-live-regions/ CSS media features to improve accessibility Learn how to incorporate user-defined settings into web interfaces. This article explores media features that track various user preferences, including animation, contrast, transparency, inversion, color schemes and forced color modes. https://a11y-blog.dev/en/articles/css-media-features-for-a11y/Thu, 09 May 2024 00:00:00 GMT https://a11y-blog.dev/en/articles/css-media-features-for-a11y/ Understanding skip links How to help users to skip large chank of a page content, whose these users are, and how to implement it on your website. https://a11y-blog.dev/en/articles/understanding-a-skip-link/Sun, 05 May 2024 00:00:00 GMT https://a11y-blog.dev/en/articles/understanding-a-skip-link/
\ No newline at end of file
+Blog on Digital Accessibility Practical advice on digital accessibility for frontend developers, QA testers and designers. Here you'll learn about methods of creating accessible and user-friendly interfaces, standards, assistive technologies and laws. https://a11y-blog.dev/Mon, 03 Jun 2024 00:00:00 GMT Role attribute with multiple values In what cases may be necessary to set multiple values for a role attribute, and how browsers and screen readers deal with this. https://a11y-blog.dev/en/articles/aria-attribute-role-with-multiple-values/Mon, 03 Jun 2024 00:00:00 GMT https://a11y-blog.dev/en/articles/aria-attribute-role-with-multiple-values/ Thinking about users with seizures and vestibular conditions What if the user gets motion sickness because of a website? What if he or she has an epileptic seizure? Let's look at what interfaces for users with seizures and vestibular conditions should look like. https://a11y-blog.dev/en/articles/how-to-protect-users-with-epilepsy-and-vd/Thu, 16 May 2024 00:00:00 GMT https://a11y-blog.dev/en/articles/how-to-protect-users-with-epilepsy-and-vd/ What you need to know about ARIA live regions If you're looking to make dynamic page content accessible, WAI-ARIA provides a solution. Previously, assistive technologies struggled with these elements, but now they can be properly handled using ARIA live regions. https://a11y-blog.dev/en/articles/aria-live-regions/Sat, 11 May 2024 00:00:00 GMT https://a11y-blog.dev/en/articles/aria-live-regions/ CSS media features to improve accessibility Learn how to incorporate user-defined settings into web interfaces. This article explores media features that track various user preferences, including animation, contrast, transparency, inversion, color schemes and forced color modes. https://a11y-blog.dev/en/articles/css-media-features-for-a11y/Thu, 09 May 2024 00:00:00 GMT https://a11y-blog.dev/en/articles/css-media-features-for-a11y/ Understanding skip links How to help users to skip large chank of a page content, whose these users are, and how to implement it on your website. https://a11y-blog.dev/en/articles/understanding-a-skip-link/Sun, 05 May 2024 00:00:00 GMT https://a11y-blog.dev/en/articles/understanding-a-skip-link/
diff --git a/en/index.html b/en/index.html
index 74c1178..95a10af 100644
--- a/en/index.html
+++ b/en/index.html
@@ -1 +1 @@
-Blog on Digital Accessibility Articles on accessibility
Hi, my name is Tatiana Fokina, or just Tanya for short. Who am I? I am a web accessibility specialist and enthusiast who likes developing user-friendly interfaces and discussing digital accessibility with others (sometimes in the middle of the night).
In this blog, I share practical tips and hacks, useful links, my thoughts, and interesting findings about accessible code, design, and much more ✨
If you have any questions about my articles or accessibility, feel free to ask me on LinkedIn and Twitter.
Resent articles
Role attribute with multiple values
In what cases may be necessary to set multiple values for a role attribute, and how browsers and screen readers deal with this.
Thinking about users with seizures and vestibular conditions
What if the user gets motion sickness because of a website? What if he or she has an epileptic seizure? Let's look at what interfaces for users with seizures and vestibular conditions should look like.
What you need to know about ARIA live regions
If you're looking to make dynamic page content accessible, WAI-ARIA provides a solution. Previously, assistive technologies struggled with these elements, but now they can be properly handled using ARIA live regions.
All articles
\ No newline at end of file
+Blog on Digital Accessibility Articles on accessibility
Hi, my name is Tatiana Fokina, or just Tanya for short. Who am I? I am a web accessibility specialist and enthusiast who likes developing user-friendly interfaces and discussing digital accessibility with others (sometimes in the middle of the night).
In this blog, I share practical tips and hacks, useful links, my thoughts, and interesting findings about accessible code, design, and much more ✨
If you have any questions about my articles or accessibility, feel free to ask me on LinkedIn and Twitter.
Resent articles
Role attribute with multiple values
In what cases may be necessary to set multiple values for a role attribute, and how browsers and screen readers deal with this.
Thinking about users with seizures and vestibular conditions
What if the user gets motion sickness because of a website? What if he or she has an epileptic seizure? Let's look at what interfaces for users with seizures and vestibular conditions should look like.
What you need to know about ARIA live regions
If you're looking to make dynamic page content accessible, WAI-ARIA provides a solution. Previously, assistive technologies struggled with these elements, but now they can be properly handled using ARIA live regions.
All articles
\ No newline at end of file
diff --git a/manifest.json b/manifest.json
index 7cee7b5..cf12e39 100644
--- a/manifest.json
+++ b/manifest.json
@@ -21,4 +21,4 @@
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "browser"
-}
\ No newline at end of file
+}
diff --git a/robots.txt b/robots.txt
index c1c6f6f..4070eaf 100644
--- a/robots.txt
+++ b/robots.txt
@@ -1,4 +1,4 @@
User-agent: *
Allow: /
-Sitemap: https://a11y-blog.dev/sitemap.xml
\ No newline at end of file
+Sitemap: https://a11y-blog.dev/sitemap.xml
diff --git a/ru/404.html b/ru/404.html
index 22053b1..902aba2 100644
--- a/ru/404.html
+++ b/ru/404.html
@@ -1 +1 @@
-Страница не найдена — Блог о цифровой доступности Страница не найдена
Скорее всего, такой страницы не существует.
\ No newline at end of file
+Страница не найдена — Блог о цифровой доступности Страница не найдена
Скорее всего, такой страницы не существует.
\ No newline at end of file
diff --git a/ru/articles/aria-attribute-role-with-multiple-values/index.html b/ru/articles/aria-attribute-role-with-multiple-values/index.html
index 312ae67..f4dfa5b 100644
--- a/ru/articles/aria-attribute-role-with-multiple-values/index.html
+++ b/ru/articles/aria-attribute-role-with-multiple-values/index.html
@@ -21,7 +21,7 @@
},
"datePublished": "2022-01-24T00:00:00.000Z",
"dateModified": "2024-06-28T00:00:00.000Z"
- } role с несколькими значениями
- ARIA
Обновлено: Недавно случайно узнала, что ARIA-атрибут role
может содержать больше одного значения. И это очень неожиданно, по крайней мере для меня.
Этот пост написала из исследовательского интереса, так что в нём нет большого количества полезных практических советов. Что-то даже лучше не применять на практике.
Небольшая справка о роли элемента
Роль содержит информацию о функциях элемента и как с ним можно взаимодействовать. К примеру, о <button>
скринридер объявит, что это кнопка, а также сможет на неё нажать.
У элементов может быть либо встроенная роль, либо явно заданная в атрибуте role
.
Есть много категорий и видов ролей, и существуют чёткие правила их явного использования. Например, нельзя менять роли при взаимодействии с элементом или задавать абстрактные (landmark
, section
, widget
и другие). Также есть роли, которые предполагают вложенные элементы. Например, в элемент с role="menu"
должен быть вложен как минимум один с menuitem
. Однако главное правило — стараться как можно реже явно задавать роли, особенно таким образом переопределять семантику элементов.
Что там в документации
В WAI-ARIA (Web Accessibility Initiative — Accessible Rich Internet Applications), как в самом очевидном источнике о role=""
, нет примеров с двумя ролями. И про несколько значений у этого атрибута пришлось поискать.
WAI-ARIA
В пункте 7.1. Атрибут роли из WAI-ARIA 1.1 собраны характеристики атрибута роли, которые нужно учитывать в языках реализации (host languages):
- Имя атрибута должно быть
role
. - Значение атрибута должно допускать список токенов в качестве значения.
- Появление имени литерала любой конкретной роли в качестве одного из токенов не должно само по себе делать недопустимым значение атрибута в синтаксисе языка реализации.
- Первый литерал имени неабстрактной роли в списке токенов атрибута
role
определяет роль в соответствии с тем, как User Agent должен обрабатывать элемент. То, как User Agent обрабатывает роли, установлено в Core Accessibility API Mappings 1.1.
В WAI-ARIA 1.2 и 1.3 нужная информация находится в пункте 8.1. Атрибут роли:
- Значение атрибута должно допускать список токенов в качестве значения.
- Появление имени литерала любой конкретной роли в качестве одного из токенов не должно само по себе делать недопустимым значение атрибута в синтаксисе языка реализации.
- Первый литерал имени неабстрактной роли в списке токенов атрибута
role
определяет роль в соответствии с тем, как User Agent должен обрабатывать элемент. То, как User Agent обрабатывает роли, установлено в Core Accessibility API Mappings 1.2.
Раз WAI-ARIA отсылает нас к другой документации, давайте почитаем теперь её.
Core Accessibility API Mappings
Core Accessibility API Mappings (Core-AAM для краткости) — это спецификация для браузеров и других User Agent. В ней описано, как они должны взаимодействовать с Accessibility API.
В пункте 5.4. Мапинг ролей из Core-AAM 1.1 есть то, что нам нужно:
Традиционно Accessibility API платформы имеют ограниченный набор заранее установленных ролей, которые ожидаются вспомогательными технологиями на этой платформе, и предоставлены могут быть только одна или две роли. Напротив, WAI-ARIA позволяет указывать несколько ролей в виде упорядоченного набора валидных токенов ролей, разделённых пробелами. Дополнительные роли — фолбэк для других ролей, что похоже на концепцию указания нескольких шрифтов на случай, если первый тип шрифта не поддерживается.
В этом пункте собраны и сами правила работы с ролями из WAI-ARIA.
- User Agent должен использовать первый токен в их последовательности в значении атрибута роли, который соответствует имени любой неабстрактной роли из таблицы мапинга ролей… Обратите внимание, что, когда роли из WAI-ARIA перезаписывают семантику языков реализации, то DOM (Document Object Model) не изменяется, только дерево доступности.
- User Agent не должен мапировать роли, которые определены в спецификации WAI-ARIA как «абстрактные», с помощью стандартного механизма ролей Accessibility API.
В Core-AAM 1.2 найдёте почти то же самое, но с большим количеством деталей про поддержку ролей разными Accessibility API.
HTML
Давным-давно в HTML-спецификации был пункт 3.2.7.3.1. ARIA-атрибут роли, который тоже описывал возможность добавлять несколько ролей для элемента:
Для каждого HTML-элемента можно указать ARIA-атрибут role
. Это атрибут роли из ARIA, который определён в спецификации в Section 5.4 Definition of Roles.
Атрибут, если он задан, должен иметь значение, которое выглядит как набор токенов, разделённых пробелами и представляющих различные роли WAI-ARIA, к которым относится элемент.
Роль WAI-ARIA, которая назначена для HTML-элемента, первая неабстрактная роль, найденная в списке значений, сгенерированных, когда атрибут role
разделён пробелами.
Пункта больше нет, но интернет помнит всё.
Перевод с документационного
Какие выводы можно сделать после путешествия по спецификациям?
- В атрибуте
role
можно указывать несколько значений. - Несколько значений перечисляется стандартно через пробел.
- Несколько ролей нужны для фолбэка. Если первая роль не поддерживается или не существует, то применяется вторая и так далее.
- Если это абстрактная роль, то браузер и скринридер её проигнорируют.
Тестируем
Давайте проверим, что будут делать браузеры и скринридеры с двумя значениями в атрибуте role
. Поэкспериментируем в Chrome 97, Firefox 96 и Safari 14 с NVDA 2021.2 и десктопным VoiceOver.
Кстати, в старых браузерах и скринридерах это не получится проверить. Они просто игнорируют role=""
с несколькими значениями. Имейте это в виду.
Разметка, которую буду тестировать, может напугать. Это проверка работы одного атрибута, так что решила хотя бы раз в жизни использовать запрещённые приёмы 😀 В реальных проектах так лучше никогда не делать. Это ужасный антипаттерн (который можно считать преступлением, ха-ха).
Оба значения существуют
<div
+ } role с несколькими значениями
- ARIA
Обновлено: Недавно случайно узнала, что ARIA-атрибут role
может содержать больше одного значения. И это очень неожиданно, по крайней мере для меня.
Этот пост написала из исследовательского интереса, так что в нём нет большого количества полезных практических советов. Что-то даже лучше не применять на практике.
Небольшая справка о роли элемента
Роль содержит информацию о функциях элемента и как с ним можно взаимодействовать. К примеру, о <button>
скринридер объявит, что это кнопка, а также сможет на неё нажать.
У элементов может быть либо встроенная роль, либо явно заданная в атрибуте role
.
Есть много категорий и видов ролей, и существуют чёткие правила их явного использования. Например, нельзя менять роли при взаимодействии с элементом или задавать абстрактные (landmark
, section
, widget
и другие). Также есть роли, которые предполагают вложенные элементы. Например, в элемент с role="menu"
должен быть вложен как минимум один с menuitem
. Однако главное правило — стараться как можно реже явно задавать роли, особенно таким образом переопределять семантику элементов.
Что там в документации
В WAI-ARIA (Web Accessibility Initiative — Accessible Rich Internet Applications), как в самом очевидном источнике о role=""
, нет примеров с двумя ролями. И про несколько значений у этого атрибута пришлось поискать.
WAI-ARIA
В пункте 7.1. Атрибут роли из WAI-ARIA 1.1 собраны характеристики атрибута роли, которые нужно учитывать в языках реализации (host languages):
- Имя атрибута должно быть
role
. - Значение атрибута должно допускать список токенов в качестве значения.
- Появление имени литерала любой конкретной роли в качестве одного из токенов не должно само по себе делать недопустимым значение атрибута в синтаксисе языка реализации.
- Первый литерал имени неабстрактной роли в списке токенов атрибута
role
определяет роль в соответствии с тем, как User Agent должен обрабатывать элемент. То, как User Agent обрабатывает роли, установлено в Core Accessibility API Mappings 1.1.
В WAI-ARIA 1.2 и 1.3 нужная информация находится в пункте 8.1. Атрибут роли:
- Значение атрибута должно допускать список токенов в качестве значения.
- Появление имени литерала любой конкретной роли в качестве одного из токенов не должно само по себе делать недопустимым значение атрибута в синтаксисе языка реализации.
- Первый литерал имени неабстрактной роли в списке токенов атрибута
role
определяет роль в соответствии с тем, как User Agent должен обрабатывать элемент. То, как User Agent обрабатывает роли, установлено в Core Accessibility API Mappings 1.2.
Раз WAI-ARIA отсылает нас к другой документации, давайте почитаем теперь её.
Core Accessibility API Mappings
Core Accessibility API Mappings (Core-AAM для краткости) — это спецификация для браузеров и других User Agent. В ней описано, как они должны взаимодействовать с Accessibility API.
В пункте 5.4. Мапинг ролей из Core-AAM 1.1 есть то, что нам нужно:
Традиционно Accessibility API платформы имеют ограниченный набор заранее установленных ролей, которые ожидаются вспомогательными технологиями на этой платформе, и предоставлены могут быть только одна или две роли. Напротив, WAI-ARIA позволяет указывать несколько ролей в виде упорядоченного набора валидных токенов ролей, разделённых пробелами. Дополнительные роли — фолбэк для других ролей, что похоже на концепцию указания нескольких шрифтов на случай, если первый тип шрифта не поддерживается.
В этом пункте собраны и сами правила работы с ролями из WAI-ARIA.
- User Agent должен использовать первый токен в их последовательности в значении атрибута роли, который соответствует имени любой неабстрактной роли из таблицы мапинга ролей… Обратите внимание, что, когда роли из WAI-ARIA перезаписывают семантику языков реализации, то DOM (Document Object Model) не изменяется, только дерево доступности.
- User Agent не должен мапировать роли, которые определены в спецификации WAI-ARIA как «абстрактные», с помощью стандартного механизма ролей Accessibility API.
В Core-AAM 1.2 найдёте почти то же самое, но с большим количеством деталей про поддержку ролей разными Accessibility API.
HTML
Давным-давно в HTML-спецификации был пункт 3.2.7.3.1. ARIA-атрибут роли, который тоже описывал возможность добавлять несколько ролей для элемента:
Для каждого HTML-элемента можно указать ARIA-атрибут role
. Это атрибут роли из ARIA, который определён в спецификации в Section 5.4 Definition of Roles.
Атрибут, если он задан, должен иметь значение, которое выглядит как набор токенов, разделённых пробелами и представляющих различные роли WAI-ARIA, к которым относится элемент.
Роль WAI-ARIA, которая назначена для HTML-элемента, первая неабстрактная роль, найденная в списке значений, сгенерированных, когда атрибут role
разделён пробелами.
Пункта больше нет, но интернет помнит всё.
Перевод с документационного
Какие выводы можно сделать после путешествия по спецификациям?
- В атрибуте
role
можно указывать несколько значений. - Несколько значений перечисляется стандартно через пробел.
- Несколько ролей нужны для фолбэка. Если первая роль не поддерживается или не существует, то применяется вторая и так далее.
- Если это абстрактная роль, то браузер и скринридер её проигнорируют.
Тестируем
Давайте проверим, что будут делать браузеры и скринридеры с двумя значениями в атрибуте role
. Поэкспериментируем в Chrome 97, Firefox 96 и Safari 14 с NVDA 2021.2 и десктопным VoiceOver.
Кстати, в старых браузерах и скринридерах это не получится проверить. Они просто игнорируют role=""
с несколькими значениями. Имейте это в виду.
Разметка, которую буду тестировать, может напугать. Это проверка работы одного атрибута, так что решила хотя бы раз в жизни использовать запрещённые приёмы 😀 В реальных проектах так лучше никогда не делать. Это ужасный антипаттерн (который можно считать преступлением, ха-ха).
Оба значения существуют
<div
role="button link"
aria-label="Это не кнопка"
tabindex="1"
diff --git a/ru/articles/css-media-features-for-a11y/index.html b/ru/articles/css-media-features-for-a11y/index.html
index 2f24311..e43b2fd 100644
--- a/ru/articles/css-media-features-for-a11y/index.html
+++ b/ru/articles/css-media-features-for-a11y/index.html
@@ -21,7 +21,7 @@
},
"datePublished": "2021-11-01T00:00:00.000Z",
"dateModified": "2024-09-05T00:00:00.000Z"
- } CSS-медиафичи для улучшения доступности
- CSS
- Юзабилити
Обновлено: Когда говорят про доступность и CSS, часто имеют в виду свойства, которые влияют на дерево доступности и скринридеры. Но есть ещё один союзник в битве за доступность интерфейсов — медиафичи.
Медиафича (media feature) — это условие для CSS-директивы @media
. Указывает на определённую характеристику устройства или браузера. К примеру, ориентацию экрана (orientation
) или режим отображения (display-mode
).
В этом посте расскажу про несколько медиафич: prefers-reduced-motion
, prefers-color-scheme
, inverted-colors
, forced-colors
, ms-high-contrast
, prefers-contrast
и prefers-reduced-transparency
. Они отслеживают настройки операционной системы. Настройки изменяют пользователи, которых не устраивает дефолтное поведение системы. К примеру, люди с особыми потребностями и те, кто испытывает дискомфорт из-за дефолтного дизайна.
Так, пользователи с эпилептическими приступами отключают анимацию из-за того, что она может вызвать приступ. А некоторые люди с астигматизмом выбирают тёмную тему и уменьшают контрастность, чтобы не болели глаза.
Учёт пользовательских настроек сделает интерфейс сайта более гибким и персонализированным. Это поможет не только повысить его уровень доступности, но и может повысить конверсию. Всегда приятно пользоваться продуктами, которые учитывают твои предпочтения.
Большинство настроек применяется только к операционной системе. Многие из них, те же анимация и уровень контрастности, не изменяют интерфейсы сайтов. Всё зависит от того, учли ли их разработчики. Как раз здесь помогают медиафичи.
Отслеживать пользовательские настройки можно и с помощью JavaScript, но не хочу раздувать пост ещё больше. Остановлюсь только на возможностях CSS.
Пользовательские настройки
Давайте сначала разберёмся, какие системные настройки можно учитывать в веб-интерфейсах уже сейчас или в будущем.
Анимация
Настройки анимации позволяют изменять её скорость или полностью отключить в системе. Не влияют на сайты, если нет специальных стилей.
Этой настройкой пользуются люди с вестибулярными нарушениями, эпилептическими приступами и с когнитивными особенностями. Особенно пользователи с синдромом дефицита внимания.
Настройка есть во всех операционных системах.
Цветовая схема
Пользователи могут также изменить настройки цветовой схемы и выбрать цвета, которые будут преобладать в системе. Это либо светлые, либо тёмные оттенки. Настройка не влияет на сайты, если на них не поддерживаются цветовые схемы.
Этой настройкой пользуются следующие категории пользователей:
- с особенностями зрения. Например, со сниженным зрением, глазными болями и повышенной светочувствительностью;
- с когнитивными особенностями. К примеру, с синдромом дефицита внимания;
- все остальные из-за эстетических предпочтений, привычки или уровня освещения.
Схемы можно выбрать во всех популярных операционных системах. В macOS и iOS есть дополнительная автоматическая тема. Если она выбрана, то днём применяется светлая тема, а ночью — тёмная.
Инвертирование цветов
Режим инвертированных цветов (inverted colors mode) заменяет системные цвета на противоположные, как на негативе. Относится к режиму экранных фильтров.
Цвета изменяются не только в системе, но и во вкладках браузера. Так что пользователи могут выбрать этот режим вместо тёмной темы. На скриншоте видно, как работает режим инверсии. Жёлтые оттенки стали синими, зелёный — малиновым, белый — чёрным.
Кто пользуется настройкой:
- люди с особенностями зрения, например, с глаукомой или глазными болями;
- пользователи с мигренями и головными болями;
- Другие пользователи из-за привычек или освещения.
Настройка есть в большинстве операционных систем. На iOS даже два вида инверсии — «Смарт-инверсия» (Smart Invert) и «Классическая инверсия» (Classic Invert). В режиме умной инверсии картинки и видео не инвертируются. В классическом инвертируется весь контент.
Цветовой режим
Режим принудительных цветов (forced colors mode) ограничивает количество цветов, чтобы повысить читаемость текста за счёт изменения контраста текста и фона. В основном используются цвета с высоким контрастом. Этот режим изменяет цвета и в системе, и на сайтах.
Кто пользуется настройкой:
- пользователи с особенностями зрения;
- люди с мигренями и головными болями;
- люди со светочувствительной эпилепсией;
- пользователи, которым нужно уменьшить визуальный шум для концентрации внимания.
Пока цветовой режим можно выбрать только в Windows. В Windows 10 и более ранних версиях это режим высокой контрастности (Windows High Contrast Mode, коротко WHCM). В Windows 11 — контрастные темы (Contrast Themes).
В режиме высокой контрастности есть несколько готовых наборов цветов:
- чёрный режим высокой контрастности (High Contrast Black);
- белый режим высокой контрастности (High Contrast White);
- высокая контрастность 1 и 2.
Технология замены цветовой палитры зависит от браузера. Она отличается в браузерах на Chromium, Firefox (движок Quantum), Internet Explorer (Trident) и в старых версиях Edge (EdgeHTML). К примеру, в Vivaldi (Chromium) белый фон сайта стал чёрным, серые ссылки и границы — ярко-жёлтыми, а обычный текст — белым вместо тёмно-серого.
В Firefox цвет изначально белого фон останется таким же, серые ссылки и границы — ярко-синими, а обычный текст — чёрный вместо тёмно-серого.
Можно изменить поведение в Firefox по умолчанию. Настройка находится в разделе с настройками языка и внешнего вида (Language and Appearence) и конкретно в подразделе «Цвета» (Colors). Откройте модальное окно кнопкой «Управлять цветами…» (Manage Colors…) и выберите чекбокс «Использовать системные цвета» (Use system colors).
В Windows 11 набор контрастных тем изменился. Появились «Водная» (Aquatic), «Пустыня» (Desert), «Сумерки» (Dusk) и «Ночное небо» (Night sky).
Если не подходят готовые темы, можно настроить их самостоятельно, в том числе уменьшить контрастность.
Контрастность
Пользователи могут отдельно повысить или понизить уровень контрастности в системе без изменения яркости экрана.
Этой настройкой пользуются пользователи:
- с особенностями зрения, например, с глаукомой;
- с мигренями и головными болями;
- со старыми или некачественными дисплеями;
- другие, кому не хватает уровня контрастности из-за освещения.
В macOS и iOS есть режим повышенной контрастности (increased contrast mode). Он увеличивает разницу между оттенками серого и делает границы элементов чётче.
Повышение контрастности влияет на внешний вид системы и веб-интерфейсов. В отличие от системных окон, на сайтах изменяется только уровень контрастности. Посмотрим на то, что станет с модальным окном в macOS в обычным режимом и в режиме повышенной контрастности. В обоих окнах открыта картинка с кричащим котом, которая называется «cute-cat.jpeg». У первого окна нет рамки, а фон панели управления с кнопками и дополнительными настройками — светло-серый. Второе окно внешне отличается от первого. У него появилась чёрная рамка, фон панели управления стал белым, а у всех кнопок и других элементов в панели появились отдельные чёрные рамки.
Прозрачность
Пользователи могут включить или выключить прозрачность фона (transparency). Непрозрачный фон часто выбирают те, кто повышает контрастность.
Прозрачный фон может увеличить когнитивную нагрузку и уменьшить читаемость текста. Поэтому этой настройкой пользуются:
- люди с особенностями зрения. Например, с астигматизмом или сниженным зрением;
- пользователи с когнитивными особенностями. К примеру, люди с дислексией или синдром дефицита внимания;
- люди с мигренями и головными болями.
Прозрачность точно настраивается в Windows и на macOS. Эти настройки не только влияют на прозрачность в интерфейсе системы, но и на сайты с браузерами. К примеру, на этом скриншоте фон навигации первого окна полупрозрачный, а у второго — непрозрачный и однотонный.
Пара слов про медиатипы
У директивы @media
есть несколько медиатипов. Они описывают устройство, на котором отображается документ.
all
. Все устройства. Задаётся автоматически, если не указать другой тип.screen
. Устройства с экранами. Например, телефоны и ноутбуки.print
. Устройства с предварительным предпросмотром и функциями печати. Те же принтеры.speech
. Устройства с синтезом речи. К примеру, скринридеры и голосовые помощники.
Медиатип speech
может быть интересен с точки зрения доступности. Пока что он не поддерживается браузерами. Раньше поддерживался браузером Opera на движке Presto, но перестал после перехода на Blink.
В будущем может пригодиться для специальных стилей для скринридеров. Например, чтобы применить к нужным элементам CSS-свойства для устройств с синтезом речи.
Медиафичи
А вот теперь переходим к медиафичам, которые помогут сделать веб-интерфейсы доступнее.
Часть из них пока не так хорошо поддерживается браузерами. Что-то может измениться в будущем с развитием CSS. В любом случае про них полезно знать.
prefers-reduced-motion
Отслеживает, выбраны ли настройки анимации для уменьшения её интенсивности. Пригодится для любой анимации на сайте. Анимацию можно замедлить или полностью отключить.
Значения prefers-reduced-motion
:
no-preference
, настройки анимации по умолчанию.reduce
, изменённые настройки анимации.
У prefers-reduced-motion
хорошая поддержка браузерам — 97 % (в 2024).
В этом примере полностью отключаю анимацию через animation: none
.
@media (prefers-reduced-motion: reduce) {
+ } CSS-медиафичи для улучшения доступности
- CSS
- Юзабилити
Обновлено: Когда говорят про доступность и CSS, часто имеют в виду свойства, которые влияют на дерево доступности и скринридеры. Но есть ещё один союзник в битве за доступность интерфейсов — медиафичи.
Медиафича (media feature) — это условие для CSS-директивы @media
. Указывает на определённую характеристику устройства или браузера. К примеру, ориентацию экрана (orientation
) или режим отображения (display-mode
).
В этом посте расскажу про несколько медиафич: prefers-reduced-motion
, prefers-color-scheme
, inverted-colors
, forced-colors
, ms-high-contrast
, prefers-contrast
и prefers-reduced-transparency
. Они отслеживают настройки операционной системы. Настройки изменяют пользователи, которых не устраивает дефолтное поведение системы. К примеру, люди с особыми потребностями и те, кто испытывает дискомфорт из-за дефолтного дизайна.
Так, пользователи с эпилептическими приступами отключают анимацию из-за того, что она может вызвать приступ. А некоторые люди с астигматизмом выбирают тёмную тему и уменьшают контрастность, чтобы не болели глаза.
Учёт пользовательских настроек сделает интерфейс сайта более гибким и персонализированным. Это поможет не только повысить его уровень доступности, но и может повысить конверсию. Всегда приятно пользоваться продуктами, которые учитывают твои предпочтения.
Большинство настроек применяется только к операционной системе. Многие из них, те же анимация и уровень контрастности, не изменяют интерфейсы сайтов. Всё зависит от того, учли ли их разработчики. Как раз здесь помогают медиафичи.
Отслеживать пользовательские настройки можно и с помощью JavaScript, но не хочу раздувать пост ещё больше. Остановлюсь только на возможностях CSS.
Пользовательские настройки
Давайте сначала разберёмся, какие системные настройки можно учитывать в веб-интерфейсах уже сейчас или в будущем.
Анимация
Настройки анимации позволяют изменять её скорость или полностью отключить в системе. Не влияют на сайты, если нет специальных стилей.
Этой настройкой пользуются люди с вестибулярными нарушениями, эпилептическими приступами и с когнитивными особенностями. Особенно пользователи с синдромом дефицита внимания.
Настройка есть во всех операционных системах.
Цветовая схема
Пользователи могут также изменить настройки цветовой схемы и выбрать цвета, которые будут преобладать в системе. Это либо светлые, либо тёмные оттенки. Настройка не влияет на сайты, если на них не поддерживаются цветовые схемы.
Этой настройкой пользуются следующие категории пользователей:
- с особенностями зрения. Например, со сниженным зрением, глазными болями и повышенной светочувствительностью;
- с когнитивными особенностями. К примеру, с синдромом дефицита внимания;
- все остальные из-за эстетических предпочтений, привычки или уровня освещения.
Схемы можно выбрать во всех популярных операционных системах. В macOS и iOS есть дополнительная автоматическая тема. Если она выбрана, то днём применяется светлая тема, а ночью — тёмная.
Инвертирование цветов
Режим инвертированных цветов (inverted colors mode) заменяет системные цвета на противоположные, как на негативе. Относится к режиму экранных фильтров.
Цвета изменяются не только в системе, но и во вкладках браузера. Так что пользователи могут выбрать этот режим вместо тёмной темы. На скриншоте видно, как работает режим инверсии. Жёлтые оттенки стали синими, зелёный — малиновым, белый — чёрным.
Кто пользуется настройкой:
- люди с особенностями зрения, например, с глаукомой или глазными болями;
- пользователи с мигренями и головными болями;
- Другие пользователи из-за привычек или освещения.
Настройка есть в большинстве операционных систем. На iOS даже два вида инверсии — «Смарт-инверсия» (Smart Invert) и «Классическая инверсия» (Classic Invert). В режиме умной инверсии картинки и видео не инвертируются. В классическом инвертируется весь контент.
Цветовой режим
Режим принудительных цветов (forced colors mode) ограничивает количество цветов, чтобы повысить читаемость текста за счёт изменения контраста текста и фона. В основном используются цвета с высоким контрастом. Этот режим изменяет цвета и в системе, и на сайтах.
Кто пользуется настройкой:
- пользователи с особенностями зрения;
- люди с мигренями и головными болями;
- люди со светочувствительной эпилепсией;
- пользователи, которым нужно уменьшить визуальный шум для концентрации внимания.
Пока цветовой режим можно выбрать только в Windows. В Windows 10 и более ранних версиях это режим высокой контрастности (Windows High Contrast Mode, коротко WHCM). В Windows 11 — контрастные темы (Contrast Themes).
В режиме высокой контрастности есть несколько готовых наборов цветов:
- чёрный режим высокой контрастности (High Contrast Black);
- белый режим высокой контрастности (High Contrast White);
- высокая контрастность 1 и 2.
Технология замены цветовой палитры зависит от браузера. Она отличается в браузерах на Chromium, Firefox (движок Quantum), Internet Explorer (Trident) и в старых версиях Edge (EdgeHTML). К примеру, в Vivaldi (Chromium) белый фон сайта стал чёрным, серые ссылки и границы — ярко-жёлтыми, а обычный текст — белым вместо тёмно-серого.
В Firefox цвет изначально белого фон останется таким же, серые ссылки и границы — ярко-синими, а обычный текст — чёрный вместо тёмно-серого.
Можно изменить поведение в Firefox по умолчанию. Настройка находится в разделе с настройками языка и внешнего вида (Language and Appearence) и конкретно в подразделе «Цвета» (Colors). Откройте модальное окно кнопкой «Управлять цветами…» (Manage Colors…) и выберите чекбокс «Использовать системные цвета» (Use system colors).
В Windows 11 набор контрастных тем изменился. Появились «Водная» (Aquatic), «Пустыня» (Desert), «Сумерки» (Dusk) и «Ночное небо» (Night sky).
Если не подходят готовые темы, можно настроить их самостоятельно, в том числе уменьшить контрастность.
Контрастность
Пользователи могут отдельно повысить или понизить уровень контрастности в системе без изменения яркости экрана.
Этой настройкой пользуются пользователи:
- с особенностями зрения, например, с глаукомой;
- с мигренями и головными болями;
- со старыми или некачественными дисплеями;
- другие, кому не хватает уровня контрастности из-за освещения.
В macOS и iOS есть режим повышенной контрастности (increased contrast mode). Он увеличивает разницу между оттенками серого и делает границы элементов чётче.
Повышение контрастности влияет на внешний вид системы и веб-интерфейсов. В отличие от системных окон, на сайтах изменяется только уровень контрастности. Посмотрим на то, что станет с модальным окном в macOS в обычным режимом и в режиме повышенной контрастности. В обоих окнах открыта картинка с кричащим котом, которая называется «cute-cat.jpeg». У первого окна нет рамки, а фон панели управления с кнопками и дополнительными настройками — светло-серый. Второе окно внешне отличается от первого. У него появилась чёрная рамка, фон панели управления стал белым, а у всех кнопок и других элементов в панели появились отдельные чёрные рамки.
Прозрачность
Пользователи могут включить или выключить прозрачность фона (transparency). Непрозрачный фон часто выбирают те, кто повышает контрастность.
Прозрачный фон может увеличить когнитивную нагрузку и уменьшить читаемость текста. Поэтому этой настройкой пользуются:
- люди с особенностями зрения. Например, с астигматизмом или сниженным зрением;
- пользователи с когнитивными особенностями. К примеру, люди с дислексией или синдром дефицита внимания;
- люди с мигренями и головными болями.
Прозрачность точно настраивается в Windows и на macOS. Эти настройки не только влияют на прозрачность в интерфейсе системы, но и на сайты с браузерами. К примеру, на этом скриншоте фон навигации первого окна полупрозрачный, а у второго — непрозрачный и однотонный.
Пара слов про медиатипы
У директивы @media
есть несколько медиатипов. Они описывают устройство, на котором отображается документ.
all
. Все устройства. Задаётся автоматически, если не указать другой тип.screen
. Устройства с экранами. Например, телефоны и ноутбуки.print
. Устройства с предварительным предпросмотром и функциями печати. Те же принтеры.speech
. Устройства с синтезом речи. К примеру, скринридеры и голосовые помощники.
Медиатип speech
может быть интересен с точки зрения доступности. Пока что он не поддерживается браузерами. Раньше поддерживался браузером Opera на движке Presto, но перестал после перехода на Blink.
В будущем может пригодиться для специальных стилей для скринридеров. Например, чтобы применить к нужным элементам CSS-свойства для устройств с синтезом речи.
Медиафичи
А вот теперь переходим к медиафичам, которые помогут сделать веб-интерфейсы доступнее.
Часть из них пока не так хорошо поддерживается браузерами. Что-то может измениться в будущем с развитием CSS. В любом случае про них полезно знать.
prefers-reduced-motion
Отслеживает, выбраны ли настройки анимации для уменьшения её интенсивности. Пригодится для любой анимации на сайте. Анимацию можно замедлить или полностью отключить.
Значения prefers-reduced-motion
:
no-preference
, настройки анимации по умолчанию.reduce
, изменённые настройки анимации.
У prefers-reduced-motion
хорошая поддержка браузерам — 97 % (в 2024).
В этом примере полностью отключаю анимацию через animation: none
.
@media (prefers-reduced-motion: reduce) {
.danger-animation {
animation: none;
}
diff --git a/ru/articles/how-to-protect-users-with-epilepsy-and-vd/index.html b/ru/articles/how-to-protect-users-with-epilepsy-and-vd/index.html
index 227f3f0..4dd85d8 100644
--- a/ru/articles/how-to-protect-users-with-epilepsy-and-vd/index.html
+++ b/ru/articles/how-to-protect-users-with-epilepsy-and-vd/index.html
@@ -21,7 +21,7 @@
},
"datePublished": "2021-07-19T00:00:00.000Z",
"dateModified": "2024-08-26T00:00:00.000Z"
- } Как не навредить пользователям с эпилепсией и вестибулярными нарушениями
- Дизайн
- Анимация
- CSS
Обновлено: Доступность помогает людям не только без проблем пользоваться интерфейсами, но и не чувствовать себя буквально плохо. С этим могут столкнуться люди с эпилепсией и вестибулярными нарушениями. В сегодняшнем посте расскажу, что значит доступность для этих пользователей.
Вестибулярные нарушения появляются и исчезают спонтанно. Например, из-за побочных эффектов от лекарств, травм головы и даже жаркой погоды. Такая же ситуация с эпилептическими приступами. Мы более-менее готовы к пользователям со скринридерами, но не можем предсказать от чего человеку станет плохо. Поэтому так важно с самого начала не создавать барьеры.
Сначала поговорим про то, что такое вестибулярные нарушения, эпилептические приступы и эпилепсия.
Вестибулярные нарушения
Многих хоть раз укачивало или было чувство тошноты. Причиной мог быть плохой сон, простуда, поездка на машине или пароме и куча других причин.
Вестибулярные нарушения (Vestibular Disorders) связаны с внутренним ухом и частью головного мозга, которая контролирует баланс и движение наших глаз. Это большая группа нарушений. В неё входят травмы головы, вестибулярная мигрень или мигрень с аурой, опухоли мозга и многое другое. Их объединяют похожие симптомы:
- головокружение;
- тошнота;
- размытое зрение;
- глазная боль;
- головные боли;
- спутанность сознания;
- проблемы с фокусом и концентрацией внимания.
Недоступные интерфейсы могут спровоцировать любой из симптомов. Факундо Коррадини в статье на A List Apart рассказывал как часами лежал в кровати с сильным головокружением после встреч с параллаксом на сайтах.
В мире живёт много людей с вестибулярными нарушениями. Одних только людей с мигренями около 15 % (статистика на 2023).
Эпилептические приступы и эпилепсия
Эпилептический приступ (Seizure) – повышенная активность одновременно множества нейронов в головном мозге. Она приводит к судорогам, параличу, временному сбою внутренних органов, потере или спутанности сознания, частичной амнезии, вспышкам страха и тревожности.
Приступы могут случаться самостоятельно или быть частью целых заболеваний. Если они часто повторяются, то это считается эпилепсией.
Немного статистики. Примерно у 6.5 % людей в мире эпилепсия (статистика на 2019).
На возникновение приступов влияют не только внутренние, но и внешние факторы. Например, свет или звуки. Приступы, спровоцированные светом, звуками и даже чтением, называются рефлекторными. Когда таких приступов много, у человека рефлекторная эпилепсия (Reflex Epilepsy, RE).
Есть несколько типов рефлекторной эпилепсии, но я сосредоточусь на светочувствительной (Photosensitive Epilepsy, PSE). Её провоцируют интенсивный мерцающий свет или движения. Она встречается у 5 % от всего количества людей с эпилепсией. Чаще всего такие приступы случаются в возрасте от 7 до 19 лет, но могут повторяться и позже.
Контент, который мигает, мерцает и вспыхивает, может привести к эпилептическому приступу, ведь он повышает электрическую активность в нейронах.
Проблемный контент
Кто же может стать виновником эпилептического приступа или другой негативной физической реакции?
- Медиа вроде видео и гифок;
- canvas;
- SVG-, CSS- и JavaScript-анимация. Например, когда рядом с текстом есть подвижные изображения или одновременно скроллятся в разных направлениях передний и задний планы — параллакс-эффекты;
- анимированная прокрутка, которая длится больше одной четвёртой (1/4) секунды или 15 миллисекунд;
- графика с контрастными полосами, клетками, спиралями и концентрическими кругами;
- высокая контрастность элементов или всего интерфейса.
Однажды я сама столкнулась с глазной болью и чувством тошноты из-за сплэшскрина в WebStorm 2021.1, хотя это всего лишь статичная картинка. Спасибо команде JetBrains, которая прислушалась к отзывам и снизила насыщенность изображений.
Больше примеров проблемных интерфейсов найдёте в статье Эйлин Уэбб «Your Interactive Makes Me Sick». Надеюсь, ваш вестибулярный аппарат справится с этим испытанием лучше, чем мой.
Как позаботиться о пользователях
Людей с эпилепсией и вестибулярными нарушениями опасно привлекать к пользовательскому тестированию. Поэтому остаётся действовать превентивно и учитывать рекомендации, которые дают эксперты.
Что же сделать для того, чтобы не навредить пользователям?
Следите за частотой вспышек. Быстрое появление яркого света называют вспышками. Они могут быть обычными (General Flash) или красными (Red Flash). Вспышки встречаются в видео и анимациях.
Обычная вспышка — это быстрое повышение яркости на 10 % и выше и её последующее снижение до 0.8 % и ниже.
Красная вспышка — пара противоположных переходов, между которыми есть насыщенный красный цвет.
Кроме вспышек есть ещё мигания (Blinks). Мигающий контент переключается между двумя состояниями. Обычно он нужен для привлечения внимания к отдельным элементам.
Частота обычных и красных вспышек, а также миганий должна быть не больше трёх (3) раз в секунду или три (3) герца (Гц). Это минимальное требование по доступности для людей со светочувствительной эпилепсией.
Лучшее решение проблемы со вспышками и миганиями — избегать их. Другой выход из ситуации — «безопасная маленькая область» (Small Safe Area). Это приём, когда вы уменьшаете видео или часть страницы с опасной анимацией. Область должна занимать меньше 10 % центральной части поля зрения или меньше 25 % от размера экрана. Дело в том, что центральная часть глаза состоит из большого количества сенсоров. Они активнее других передают сигналы в зрительную кору и могут перегрузить нейроны.
Уменьшение области вспышек и миганий не лучшее решение, так как пользователь может зайти на сайт с мобильного устройства и поднести его слишком близко к глазам.
Что касается миганий, то, если они длятся недолго и автоматически останавливаются, всё хорошо.
Проверить видео и анимацию можете в бесплатной программе Photosensitive Epilepsy Analysis Tool (PEAT). Правда, она подходит только для некоммерческих целей. Для коммерческих есть платная Harding Test.
Выключите анимацию. Можно отключить анимацию, если она не ключевой функционал. Для этого пригодится медиафича prefers-reduced-motion
. Она проверяет выбор настроек «Уменьшить движение» (Reduce Motion) в macOS или «Показывать анимацию» (Show Animations) в Windows. Посмотреть на то, как работает медиафича, можно в демке от W3C.
Железобетонных значений для скорости, плавности и других свойств анимации нет. Так что можно воспользоваться опытом других разработчиков или спросить совета у пользователей.
Вариант один (1): только prefers-reduced-motion
. Его предлагает Вал Хед.
@media (prefers-reduced-motion: reduce) {
+ } Как не навредить пользователям с эпилепсией и вестибулярными нарушениями
- Дизайн
- Анимация
- CSS
Обновлено: Доступность помогает людям не только без проблем пользоваться интерфейсами, но и не чувствовать себя буквально плохо. С этим могут столкнуться люди с эпилепсией и вестибулярными нарушениями. В сегодняшнем посте расскажу, что значит доступность для этих пользователей.
Вестибулярные нарушения появляются и исчезают спонтанно. Например, из-за побочных эффектов от лекарств, травм головы и даже жаркой погоды. Такая же ситуация с эпилептическими приступами. Мы более-менее готовы к пользователям со скринридерами, но не можем предсказать от чего человеку станет плохо. Поэтому так важно с самого начала не создавать барьеры.
Сначала поговорим про то, что такое вестибулярные нарушения, эпилептические приступы и эпилепсия.
Вестибулярные нарушения
Многих хоть раз укачивало или было чувство тошноты. Причиной мог быть плохой сон, простуда, поездка на машине или пароме и куча других причин.
Вестибулярные нарушения (Vestibular Disorders) связаны с внутренним ухом и частью головного мозга, которая контролирует баланс и движение наших глаз. Это большая группа нарушений. В неё входят травмы головы, вестибулярная мигрень или мигрень с аурой, опухоли мозга и многое другое. Их объединяют похожие симптомы:
- головокружение;
- тошнота;
- размытое зрение;
- глазная боль;
- головные боли;
- спутанность сознания;
- проблемы с фокусом и концентрацией внимания.
Недоступные интерфейсы могут спровоцировать любой из симптомов. Факундо Коррадини в статье на A List Apart рассказывал как часами лежал в кровати с сильным головокружением после встреч с параллаксом на сайтах.
В мире живёт много людей с вестибулярными нарушениями. Одних только людей с мигренями около 15 % (статистика на 2023).
Эпилептические приступы и эпилепсия
Эпилептический приступ (Seizure) – повышенная активность одновременно множества нейронов в головном мозге. Она приводит к судорогам, параличу, временному сбою внутренних органов, потере или спутанности сознания, частичной амнезии, вспышкам страха и тревожности.
Приступы могут случаться самостоятельно или быть частью целых заболеваний. Если они часто повторяются, то это считается эпилепсией.
Немного статистики. Примерно у 6.5 % людей в мире эпилепсия (статистика на 2019).
На возникновение приступов влияют не только внутренние, но и внешние факторы. Например, свет или звуки. Приступы, спровоцированные светом, звуками и даже чтением, называются рефлекторными. Когда таких приступов много, у человека рефлекторная эпилепсия (Reflex Epilepsy, RE).
Есть несколько типов рефлекторной эпилепсии, но я сосредоточусь на светочувствительной (Photosensitive Epilepsy, PSE). Её провоцируют интенсивный мерцающий свет или движения. Она встречается у 5 % от всего количества людей с эпилепсией. Чаще всего такие приступы случаются в возрасте от 7 до 19 лет, но могут повторяться и позже.
Контент, который мигает, мерцает и вспыхивает, может привести к эпилептическому приступу, ведь он повышает электрическую активность в нейронах.
Проблемный контент
Кто же может стать виновником эпилептического приступа или другой негативной физической реакции?
- Медиа вроде видео и гифок;
- canvas;
- SVG-, CSS- и JavaScript-анимация. Например, когда рядом с текстом есть подвижные изображения или одновременно скроллятся в разных направлениях передний и задний планы — параллакс-эффекты;
- анимированная прокрутка, которая длится больше одной четвёртой (1/4) секунды или 15 миллисекунд;
- графика с контрастными полосами, клетками, спиралями и концентрическими кругами;
- высокая контрастность элементов или всего интерфейса.
Однажды я сама столкнулась с глазной болью и чувством тошноты из-за сплэшскрина в WebStorm 2021.1, хотя это всего лишь статичная картинка. Спасибо команде JetBrains, которая прислушалась к отзывам и снизила насыщенность изображений.
Больше примеров проблемных интерфейсов найдёте в статье Эйлин Уэбб «Your Interactive Makes Me Sick». Надеюсь, ваш вестибулярный аппарат справится с этим испытанием лучше, чем мой.
Как позаботиться о пользователях
Людей с эпилепсией и вестибулярными нарушениями опасно привлекать к пользовательскому тестированию. Поэтому остаётся действовать превентивно и учитывать рекомендации, которые дают эксперты.
Что же сделать для того, чтобы не навредить пользователям?
Следите за частотой вспышек. Быстрое появление яркого света называют вспышками. Они могут быть обычными (General Flash) или красными (Red Flash). Вспышки встречаются в видео и анимациях.
Обычная вспышка — это быстрое повышение яркости на 10 % и выше и её последующее снижение до 0.8 % и ниже.
Красная вспышка — пара противоположных переходов, между которыми есть насыщенный красный цвет.
Кроме вспышек есть ещё мигания (Blinks). Мигающий контент переключается между двумя состояниями. Обычно он нужен для привлечения внимания к отдельным элементам.
Частота обычных и красных вспышек, а также миганий должна быть не больше трёх (3) раз в секунду или три (3) герца (Гц). Это минимальное требование по доступности для людей со светочувствительной эпилепсией.
Лучшее решение проблемы со вспышками и миганиями — избегать их. Другой выход из ситуации — «безопасная маленькая область» (Small Safe Area). Это приём, когда вы уменьшаете видео или часть страницы с опасной анимацией. Область должна занимать меньше 10 % центральной части поля зрения или меньше 25 % от размера экрана. Дело в том, что центральная часть глаза состоит из большого количества сенсоров. Они активнее других передают сигналы в зрительную кору и могут перегрузить нейроны.
Уменьшение области вспышек и миганий не лучшее решение, так как пользователь может зайти на сайт с мобильного устройства и поднести его слишком близко к глазам.
Что касается миганий, то, если они длятся недолго и автоматически останавливаются, всё хорошо.
Проверить видео и анимацию можете в бесплатной программе Photosensitive Epilepsy Analysis Tool (PEAT). Правда, она подходит только для некоммерческих целей. Для коммерческих есть платная Harding Test.
Выключите анимацию. Можно отключить анимацию, если она не ключевой функционал. Для этого пригодится медиафича prefers-reduced-motion
. Она проверяет выбор настроек «Уменьшить движение» (Reduce Motion) в macOS или «Показывать анимацию» (Show Animations) в Windows. Посмотреть на то, как работает медиафича, можно в демке от W3C.
Железобетонных значений для скорости, плавности и других свойств анимации нет. Так что можно воспользоваться опытом других разработчиков или спросить совета у пользователей.
Вариант один (1): только prefers-reduced-motion
. Его предлагает Вал Хед.
@media (prefers-reduced-motion: reduce) {
*:not(.safe-animation),
*:not(.safe-animation)::before,
*:not(.safe-animation)::after {
diff --git a/ru/articles/index.html b/ru/articles/index.html
index c50988b..52ae9af 100644
--- a/ru/articles/index.html
+++ b/ru/articles/index.html
@@ -1 +1 @@
-Все статьи — Блог о цифровой доступности Все статьи
Клавиатура
Разбираемся с критерием про доступность интерфейса для клавиатуры.
Внешний вид фокуса
Как должны выглядеть элементы при фокусе с клавиатуры по мнению WCAG 2.2.
Информация и взаимосвязи
Почему важно подкреплять визуальное представление элементов правильной разметкой.
Название страницы
Почему у страниц должны быть названия и как их правильно составлять.
Видимый фокус
Разбираемся с критерием о видимом клавиатурном фокусе у интерактивных элементов.
Нетекстовое содержимое
Что такое нетекстовое содержимое и текстовые альтернативы.
Клавиша символа в клавиатурном сокращении
Почему клавиатурные сокращения с одним печатным символом, буквой или цифрой — барьер для пользователей.
Сенсорные характеристики
Что такое сенсорные характеристики в инструкциях и как не создать этот барьер.
Размер цели
Что такое размер цели, и как не создать такой барьер для пользователей вашего сайта.
Консистентная идентификация
Что такое консистентная идентификация на страницах и как не запутать пользователей инструкциями.
role с несколькими значениями
Разберёмся с несколькими значениями у атрибута для роли. В каких случаях это пригодится, и какие отношения с двумя ролями у браузеров и скринридеров.
CSS-медиафичи для улучшения доступности
Какие пользовательские настройки бывают и как их учитывать в веб-интерфейсах. Узнаете про медиафичи, которые отслеживают настройки анимации, контрастности, прозрачности, инверсию, цветовую схему и режим принудительных цветов.
Разбираемся со skip link
Как пропустить большую навигацию с помощью skip link, кому нужны такие ссылки и как их добавить на свой сайт.
Как не навредить пользователям с эпилепсией и вестибулярными нарушениями
Что, если пользователя укачивает из-за сайта? А вдруг у него случится эпилептический приступ? Давайте разберёмся с тем, какими должны быть интерфейсы для пользователей с эпилепсией и вестибулярными нарушениями.
\ No newline at end of file
+Все статьи — Блог о цифровой доступности Все статьи
Клавиатура
Разбираемся с критерием про доступность интерфейса для клавиатуры.
Внешний вид фокуса
Как должны выглядеть элементы при фокусе с клавиатуры по мнению WCAG 2.2.
Информация и взаимосвязи
Почему важно подкреплять визуальное представление элементов правильной разметкой.
Название страницы
Почему у страниц должны быть названия и как их правильно составлять.
Видимый фокус
Разбираемся с критерием о видимом клавиатурном фокусе у интерактивных элементов.
Нетекстовое содержимое
Что такое нетекстовое содержимое и текстовые альтернативы.
Клавиша символа в клавиатурном сокращении
Почему клавиатурные сокращения с одним печатным символом, буквой или цифрой — барьер для пользователей.
Сенсорные характеристики
Что такое сенсорные характеристики в инструкциях и как не создать этот барьер.
Размер цели
Что такое размер цели, и как не создать такой барьер для пользователей вашего сайта.
Консистентная идентификация
Что такое консистентная идентификация на страницах и как не запутать пользователей инструкциями.
role с несколькими значениями
Разберёмся с несколькими значениями у атрибута для роли. В каких случаях это пригодится, и какие отношения с двумя ролями у браузеров и скринридеров.
CSS-медиафичи для улучшения доступности
Какие пользовательские настройки бывают и как их учитывать в веб-интерфейсах. Узнаете про медиафичи, которые отслеживают настройки анимации, контрастности, прозрачности, инверсию, цветовую схему и режим принудительных цветов.
Разбираемся со skip link
Как пропустить большую навигацию с помощью skip link, кому нужны такие ссылки и как их добавить на свой сайт.
Как не навредить пользователям с эпилепсией и вестибулярными нарушениями
Что, если пользователя укачивает из-за сайта? А вдруг у него случится эпилептический приступ? Давайте разберёмся с тем, какими должны быть интерфейсы для пользователей с эпилепсией и вестибулярными нарушениями.
\ No newline at end of file
diff --git a/ru/articles/understanding-a-skip-link/index.html b/ru/articles/understanding-a-skip-link/index.html
index adad00d..46a0259 100644
--- a/ru/articles/understanding-a-skip-link/index.html
+++ b/ru/articles/understanding-a-skip-link/index.html
@@ -21,7 +21,7 @@
},
"datePublished": "2021-08-23T00:00:00.000Z",
"dateModified": "2024-06-13T00:00:00.000Z"
- } Разбираемся со skip link
- Паттерны
- HTML
- CSS
Обновлено: В вебе есть много небольших, но полезных доступных паттернов. И один из них — ссылка для пропуска контента или скип линк (skip link). Это гиперссылка, которая ведёт к основному содержанию страницы и помогает пропустить объёмный, часто повторяющийся контент. Её главная цель — экономия времени пользователей.
Какой контент считается объёмным? Навигационное меню с логотипом и кучей ссылок, громоздкая сложная таблица, буквенные указатели, списки с главами или техническими характеристиками. Чаще всего skip link полезна для пропуска навигации по сайту в хедере.
Исключения — меню в футере и небольшая навигация в хедере, которая состоит из пары ссылок и логотипа. В случае футера можно вернуться к началу страницы с помощью клавиш, жестов и других встроенных возможностей браузеров. А небольшая навигация не отнимет много времени у пользователей.
В теории всё просто, но на практике несколько сложнее. Давайте попробуем разобраться со всем по порядку.
Теория
Послушаем WCAG 2.2
В руководстве по доступности есть два критерия, связанные со skip link. Первый касается их косвенно, а второй напрямую.
- Критерий 2.1.1. Клавиатура (A). Вся функциональность контента доступна для клавиатуры и не зависит от пауз между нажатиями клавиш.
- Критерий 2.4.1. Пропуск блоков (А). Доступен механизм пропуска блоков контента, которые повторяются на нескольких страницах.
Механизмы пропуска блоков
Есть два механизма:
- навигация по ориентирам (landmarks);
- skip link.
Первый способ доступен для пользователей скринридеров. Ориентиры добавляются с помощью семантических тегов или благодаря ARIA. У второго механизма аудитория больше. Это не только пользователи с особенностями зрения.
Можно встретить совет о том, что skip link не нужна на сайте с хорошей семантической вёрсткой. Это не совсем верно. Не все пользователи скринридеров знают о шорткатах для открытия меню с ориентирами, а у других пользователей клавиатуры такой возможности нет. К тому же, чем больше вариантов навигации, тем лучше.
Кому это нужно
Если коротко, то всем, кто последовательно навигируется по страницам и не может быстро пропустить контент. Если развёрнуто, то четырём категориям пользователей. Это:
- Пользователи скринридеров, которые перемещаются по десктопным сайтам с помощью клавиатуры, а по мобильным — касаниями, тапами и свайпами.
- Пользователи с моторными нарушениями, которые пользуются клавиатурой, выносными компьютерными кнопками и другими переключателями.
- Любые другие пользователи клавиатуры. Они могут быть продвинутого уровня или у них временно сломалась мышка.
- Пользователи экранных луп, которые используют для навигации клавиатуру.
Представьте, что используете для навигации клавиатуру и зашли на сайт интернет-магазина, например, Ozon. Вы нашли нужный товар, перешли к нему и снова оказались в начале страницы. Примерно 40 табов и вот наконец можно узнать больше про понравившийся рюкзак. Со skip link вы бы оказались в нужном месте в одно нажатие и не заснули по пути.
Требования к skip link
- Находится на первом месте в порядке табуляции.
- Ведёт сразу к основному контенту и устанавливает фокус на нём. Она эффективнее, если на странице одна основная область —
<main>
. - Может располагаться в основной области страницы. В этом случаем она пропускает нужный блок и ведёт в начало следующего.
- Понятно называется и хорошо описывает, куда ведёт.
- Может быть всегда видна, а может появляться при фокусе с клавиатуры. В обоих случаях отвечает критериям WCAG.
- Можно добавлять несколько таких ссылок. Например, одна ведёт к основному контенту, вторая — к поисковой строке. Не стоит перебарщивать с количеством, иначе в ссылках нет смысла.
- Не должна мешать пользователям мыши. Это дискуссионное требование, но в нём есть разумное зерно. Если такая ссылка всегда видна, то может запутать пользователей мышки. Они не знакомы с этим паттерном, а ещё один способ прокрутки к основному контенту им не нужен.
Практика
В проекте уже должен поддерживаться фокус с клавиатуры и использоваться семантическая вёрстка. Без этого skip link бесполезна.
Размечаем страницу
Перед тем, как перейти к разметке, пара слов про текст ссылки. На англоязычных сайтах чаще всего используют «Skip to main content» или «Skip to content». Кажется, что самые подходящие эквиваленты в русском — «Перейти к основному контенту» или более краткое «К основному контенту». «Содержание» — широкое понятие и означает содержимое страницы или оглавление. «Контент» лучше отражает, куда ведёт ссылка.
Ещё несколько вариантов названия:
- пропустить навигацию (Skip navigation);
- пропустить основную навигацию (Skip main navigation);
- пропустить ссылки в навигации (Skip navigation links).
Теперь поговорим о разметке.
Практическая реализация skip link — якорная ссылка. Лучше добавить её в начало <body>
или <header>
, если это первый элемент на странице. В примерах буду добавлять её в начало хедера.
<header>
+ } Разбираемся со skip link
- Паттерны
- HTML
- CSS
Обновлено: В вебе есть много небольших, но полезных доступных паттернов. И один из них — ссылка для пропуска контента или скип линк (skip link). Это гиперссылка, которая ведёт к основному содержанию страницы и помогает пропустить объёмный, часто повторяющийся контент. Её главная цель — экономия времени пользователей.
Какой контент считается объёмным? Навигационное меню с логотипом и кучей ссылок, громоздкая сложная таблица, буквенные указатели, списки с главами или техническими характеристиками. Чаще всего skip link полезна для пропуска навигации по сайту в хедере.
Исключения — меню в футере и небольшая навигация в хедере, которая состоит из пары ссылок и логотипа. В случае футера можно вернуться к началу страницы с помощью клавиш, жестов и других встроенных возможностей браузеров. А небольшая навигация не отнимет много времени у пользователей.
В теории всё просто, но на практике несколько сложнее. Давайте попробуем разобраться со всем по порядку.
Теория
Послушаем WCAG 2.2
В руководстве по доступности есть два критерия, связанные со skip link. Первый касается их косвенно, а второй напрямую.
- Критерий 2.1.1. Клавиатура (A). Вся функциональность контента доступна для клавиатуры и не зависит от пауз между нажатиями клавиш.
- Критерий 2.4.1. Пропуск блоков (А). Доступен механизм пропуска блоков контента, которые повторяются на нескольких страницах.
Механизмы пропуска блоков
Есть два механизма:
- навигация по ориентирам (landmarks);
- skip link.
Первый способ доступен для пользователей скринридеров. Ориентиры добавляются с помощью семантических тегов или благодаря ARIA. У второго механизма аудитория больше. Это не только пользователи с особенностями зрения.
Можно встретить совет о том, что skip link не нужна на сайте с хорошей семантической вёрсткой. Это не совсем верно. Не все пользователи скринридеров знают о шорткатах для открытия меню с ориентирами, а у других пользователей клавиатуры такой возможности нет. К тому же, чем больше вариантов навигации, тем лучше.
Кому это нужно
Если коротко, то всем, кто последовательно навигируется по страницам и не может быстро пропустить контент. Если развёрнуто, то четырём категориям пользователей. Это:
- Пользователи скринридеров, которые перемещаются по десктопным сайтам с помощью клавиатуры, а по мобильным — касаниями, тапами и свайпами.
- Пользователи с моторными нарушениями, которые пользуются клавиатурой, выносными компьютерными кнопками и другими переключателями.
- Любые другие пользователи клавиатуры. Они могут быть продвинутого уровня или у них временно сломалась мышка.
- Пользователи экранных луп, которые используют для навигации клавиатуру.
Представьте, что используете для навигации клавиатуру и зашли на сайт интернет-магазина, например, Ozon. Вы нашли нужный товар, перешли к нему и снова оказались в начале страницы. Примерно 40 табов и вот наконец можно узнать больше про понравившийся рюкзак. Со skip link вы бы оказались в нужном месте в одно нажатие и не заснули по пути.
Требования к skip link
- Находится на первом месте в порядке табуляции.
- Ведёт сразу к основному контенту и устанавливает фокус на нём. Она эффективнее, если на странице одна основная область —
<main>
. - Может располагаться в основной области страницы. В этом случаем она пропускает нужный блок и ведёт в начало следующего.
- Понятно называется и хорошо описывает, куда ведёт.
- Может быть всегда видна, а может появляться при фокусе с клавиатуры. В обоих случаях отвечает критериям WCAG.
- Можно добавлять несколько таких ссылок. Например, одна ведёт к основному контенту, вторая — к поисковой строке. Не стоит перебарщивать с количеством, иначе в ссылках нет смысла.
- Не должна мешать пользователям мыши. Это дискуссионное требование, но в нём есть разумное зерно. Если такая ссылка всегда видна, то может запутать пользователей мышки. Они не знакомы с этим паттерном, а ещё один способ прокрутки к основному контенту им не нужен.
Практика
В проекте уже должен поддерживаться фокус с клавиатуры и использоваться семантическая вёрстка. Без этого skip link бесполезна.
Размечаем страницу
Перед тем, как перейти к разметке, пара слов про текст ссылки. На англоязычных сайтах чаще всего используют «Skip to main content» или «Skip to content». Кажется, что самые подходящие эквиваленты в русском — «Перейти к основному контенту» или более краткое «К основному контенту». «Содержание» — широкое понятие и означает содержимое страницы или оглавление. «Контент» лучше отражает, куда ведёт ссылка.
Ещё несколько вариантов названия:
- пропустить навигацию (Skip navigation);
- пропустить основную навигацию (Skip main navigation);
- пропустить ссылки в навигации (Skip navigation links).
Теперь поговорим о разметке.
Практическая реализация skip link — якорная ссылка. Лучше добавить её в начало <body>
или <header>
, если это первый элемент на странице. В примерах буду добавлять её в начало хедера.
<header>
<a href="#main-content" class="skip-link">
К основному контенту
</a>
diff --git a/ru/articles/wcag-character-key/index.html b/ru/articles/wcag-character-key/index.html
index 3aa52a0..4208104 100644
--- a/ru/articles/wcag-character-key/index.html
+++ b/ru/articles/wcag-character-key/index.html
@@ -21,4 +21,4 @@
},
"datePublished": "2022-11-14T00:00:00.000Z",
"dateModified": "2024-08-27T00:00:00.000Z"
- } Клавиша символа в клавиатурном сокращении
- WCAG
- Дизайн
- Клавиатура
Обновлено: В этом посте из серии про разбор Руководств по доступности веб-контента (Web Content Accessibility Guidelines, коротко WCAG) расскажу про критерий 2.1.4: клавиша символа в клавиатурном сокращении.
Это базовый критерий уровня A, и он связан с принципом управляемости и с доступностью управления с клавиатуры.
Коротко о критерии
Если используете в клавиатурном сокращении только букву, символ или цифру, у пользователя должна быть возможность его отключить, переназначить или применить только при фокусе на элементе.
Подробнее
Критерий про клавишу символа касается сайтов, программ и приложений, где есть авторские клавиатурные сокращения. Они часто встречаются в редакторах кода, текстовых редакторах и почтовых клиентах.
Критерий подразумевает, что лучше всего использовать клавиатурные сокращения с клавишами-модификаторами. То есть, сокращения не должны состоять только из букв, символов и любых других клавиш с тем, что можно напечатать (non-printable key).
На реальных сайтах и в приложениях часто удобнее и привычнее использовать клавиши с буквами. Например, в видеоплеерах. В этом случае можно сделать следующее:
- добавить на странице или в настройки элемент, который отключает клавиатурные сокращения;
- дать возможность перенастроить сокращения.
Если клавиатурное сокращение с буквой, символом или цифрой срабатывает только при фокусе на элементе, это тоже соответствует критерию. Например выпадающее меню, которое открывается при клике на кнопке «Открыть меню» или при нажатии на клавишу m, когда кнопка в фокусе.
Кому это важно
- Пользователи, которые взаимодействуют с интерфейсом голосом. Например, используют речевой ввод.
- Все пользователи клавиатуры — пользователи скринридеров, экранных луп, пользователи с особенностями моторики, например, с церебральным параличом, ампутированными пальцами, протезами.
- Пользователи небольших портативных клавиатур.
- Люди с когнитивными особенностями, которым удобно назначать одни и те же клавиши для одной команды на разных сайтах и в приложениях.
В первую очередь критерий связан с пользователями голосового управления. В этих программах есть несколько режимов. Один только для команд, другой для голосового ввода текста, и ещё есть смешанный режим, в котором можно надиктовывать текст и выполнять команды. Чаще всего используют смешанный режим. Он удобнее, не нужно переключаться между разными режимами.
При наборе слова по буквам вместо буквы может выполнится одна или даже несколько команд, если в клавиатурных сокращениях используются только клавиши с буквами. Команды могут активировать даже посторонние звуки, если включён микрофон.
Как избежать барьер
Чаще всего проблемы с клавиатурными сокращениями возникают на этапе проработки дизайна взаимодействия (interaction design) и написания кода.
Важно найти баланс между лёгкостью нажатия на клавиши и тем, как при этом сложно сделать ошибку. Можно всегда использовать клавиши-модификаторы в любых клавиатурных сокращениях или дать пользователям гибкие настройки для команд, когда их много.
Примеры соответствия критерию
- На сайте есть модальное окно с настройками, его можно открыть при помощи Alt + O.
- В веб-приложении клавиша / (косая черта) делает фокус на поле поиска, но пользователь может её отключить с помощью переключателя в настройках своего профиля.
- На сайте видео разворачивается на весь экран с помощью F, но пользователь может зайти в настройки и изменить клавиши для этой команды.
В Gmail много клавиатурных сокращений из одного символа или знака. Например, / (косая черта) для поиска по письмам или g для перехода к следующей странице. Эти сокращения можно отключить и настроить. В списке всех настроек откройте вкладку с продвинутыми настройками (advanced) и включите кастомные клавиатурные сокращения (custom keyboard shortcuts). После появится отдельная вкладка «Клавиатурные сокращения» («Keyboard Shortcuts»), в которой можно переназначить клавиши для разных команд.
Клавиши собраны в одну таблицу. В первой колонке хранятся текущие клавиатурные сокращения, по умолчанию она пустая. Во второй колонке «Действия» перечислены команды. Например, открыть окно, искать контакты в чате, упорядочить, искать электронное письмо и так далее. В последней колонке «Клавиша/клавишы» перечислены клавиши по умолчанию и их альтернативы. Например, знак вопроса, Esc, косая черта, стрелка вниз, вправо, влево и тому подобное. Все поля с клавишами кликабельные, в них можно ввести свои варианты сокращений.
В GitHub тоже есть команды, которые выполняются одной клавишей с буквой или знаком. Например, s делает фокус на поле поиска, а . (точка) открывает редактор кода. В настройках профиля можно отключить клавиатурные сокращения или изменить их. Для этого зайдите в настройки профиля, выберите вкладку «Accessibility» («Доступность») и отожмите чекбокс «Character Keys» («Клавиши символов»). Теперь можно настроить клавиши-модификаторы для клавиатурных сокращений в подразделе «Command Palette» («Палитра команд»). Для этого надо выбрать из выпадающих списков «Search mode» («Режим поиска») и «Command mode» («Режим команд») подходящую опцию.
На скриншоте показано, как это выглядит в самом интерфейсе GitHub. Рядом со всеми элементами управления есть подсказки. Например, про то, что клавиши по умолчанию можно отключить и взамен использовать команды с клавишами-модификаторами. В выпадающем списке «Режим команд» есть несколько клавиш на выбор. Это Ctrl Shift k (по умолчанию), Ctrl k, Ctrl Alt k, Ctrl p, Ctrl Shift p и пункт для отключения шорткатов.
Примеры барьеров
- На сайте есть поиск, к которому можно перейти с помощью клавиши S. У пользователя нет возможности отключить это клавиатурное сокращение или переназначить клавишу.
- В приложении есть кнопка для открытия модального окна. Ещё окно открывается клавишей + (плюс), даже когда кнопка не в фокусе.
В десктопной версии YouTube есть много клавиатурных сокращений. Например, F раскрывает видео на весь экран, k ставит видео на паузу или продолжает воспроизведение, c включает или выключает субтитры, а , (запятая) перематывает к следующему кадру, когда видео на паузе. Однако на сайте нельзя отключить клавиатурные сокращения или переназначить клавиши.
Список сокращений спрятан в модальном окне. Визуально список выглядит как таблица, состоящая из двух колонок без заголовков. В первой перечислены команды, во второй — клавиши. Например, переключить воспроизведение/паузу — k, перемотать на десять (10) секунд — j и так далее.
Как тестировать
Протестировать критерий поможет ручное или автоматическое тестирование.
- Найдите страницы или экраны, где есть клавиатурные сокращения.
- Найдите все сокращения, где используются только клавиши с буквами, символами или цифрами.
- Проверьте, как выполняются команды. Это происходит только при фокусе на элементе или на всей странице.
- Если команда срабатывает без фокуса на элементе, убедитесь, что её можно отключить или переназначить.
Проще всего поискать во всех .js-файлах по ключевым словам, связанным с клавишами. Например, keydown
, keyup
или keypress
. Ещё можно написать скрипт, который будет нажимать все возможные клавиши на страницах и выводить, например, в консоль сообщение о том, какие клавиши он обнаружил. Так это сделано в довольно старом букмарклете Trigger character key shortcuts.
Что почитать
- Success Criterion 2.1.4 Character Key Shortcuts, WCAG 2.2
- Understanding Success Criterion 2.1.4: Character Key Shortcuts, WCAG 2.2
- Provide a way to turn off character key shortcuts, Access Guide
- Exploring WCAG 2.1 — 2.1.4 Character Key Shortcuts, Knowbility
- Keyboard shortcuts need modifier keys, Хиде де Врис
Другие статьи
- Нетекстовое содержимое Предыдущая
- Сенсорные характеристики Следующая