17

The following article is from an interesting fact about iCSS front-end, author SbCoco

iCSS front-end fun facts are more than CSS

This article is a little bit longer, please read it carefully, you should be rewarded~

In fact, the title should be called, Web User Experience Design Improvement Guide.

A Web page, an APP, I want others to use it cool, which is the so-called good user experience, I think it may include but not limited to:

  • Rapid opening speed
  • Bright UI design
  • Cool animation effects
  • Rich personalized settings
  • Convenient operation
  • Intimate details
  • Pay attention to the disabled, good accessibility
  • ...

The so-called user experience design, in fact, is a relatively empty concept, is adhering to the user-centric thinking one design means to target the needs of the user to perform design. The design process focuses on user-centeredness, and the concept of user experience enters the entire process from the earliest stage of development, and runs through it throughout.

Good user experience design is the result of joint efforts in every aspect of the product.

Excluding some that are difficult to accomplish overnight, this article will show the , interaction details, , accessibility, , and list some useful experiences accumulated in the actual development process. Through this article, you will be able to gain:

  1. Learn how some small details affect the user experience
  2. Learn how to improve the user experience of the page with the smallest possible development changes
  3. Learned some excellent interaction design details
  4. Understand the meaning of basic accessibility features and page accessibility
  5. Understand the basic methods to improve page accessibility

Page display

As far as the presentation of the entire page and the presentation of the content of the page are concerned, there are some small details that need our attention.

overall arrangement

Let's take a look at some layout-related issues first.

For most PC-side projects, the first thing we need to consider is definitely the outermost layer of package. Suppose it is .g-app-wrapper .

<div class="g-app-wrapper">
    <!-- 内部内容 -->
</div>

First of all, for .g-app-wrapper , there are several points that we must figure out before the project is developed:

  1. Is the project a full-screen layout or a fixed-width layout?
  2. For a full-screen layout, what is the minimum width that needs to be adapted?

For fixed-width layout, it is more convenient. Assuming that the width is set to 1200px , then:

.g-app-wrapper {
    width: 1200px;
    margin: 0 auto;
}

Use margin: 0 auto realize the horizontal centering of the layout. When the screen width is greater than 1200px , leave blank on both sides. Of course, when the screen width is less than 1200px , a scroll bar appears to ensure that the internal content is not messy.

图片

For modern layouts, more are full-screen layouts. In fact, this layout is now more advocated, that is, an adaptive layout that can vary with the size and capabilities of the user's device.

Generally speaking, there are two left and right columns, the left side is fixed width, and the right side is adaptive to the remaining width. Of course, there will be a minimum width. Then, its layout should be like this:

<div class="g-app-wrapper">
    <div class="g-sidebar"></div>
    <div class="g-main"></div>
</div>
.g-app-wrapper {
    display: flex;
    min-width: 1200px;
}
.g-sidebar {
    flex-basis: 250px;
    margin-right: 10px;
}
.g-main {
    flex-grow: 1;
}

图片

flex-grow: 1 under the flex layout, allowing .main to expand and contract, occupying the remaining space, and using min-width ensure the minimum width of the entire container.

Of course, this is the most basic adaptive layout. For modern layouts, we should consider as many scenarios as possible. Do:

图片

Bottom footer

The following scenario is also a very common scenario.

There is a footer on the page. If the content height of the entire page is less than the height of the window, the footer is fixed at the bottom of the window. If the content height of the entire page is greater than the height of the window, the footer is arranged normally (that is, it needs to be scrolled to the bottom). To see the footer).

See the effect:

图片

Ah, if this requirement can use flex it, use justify-content: space-between can solve the same token use margin-top: auto is also very easy to do:

<div class="g-container">
    <div class="g-real-box">
        ...
    </div>
    <div class="g-footer"></div>
</div>
.g-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
}

.g-footer {
    margin-top: auto;
    flex-shrink: 0;
    height: 30px;
    background: deeppink;
}

Codepen Demo -- sticky footer by flex margin auto[1]

Of course, there are many ways to implement it, and only one recommended solution is given here.

Handling dynamic content-long text

For all text display interfaces that receive back-end interface fields. All need to consider comprehensive (defensive programming: all external data is untrustworthy), the normal situation is as follows, there is no problem.

图片

But have we considered that the text will be too long? Will it wrap or wrap if it's too long?

图片

For single-line text , use single-line omission:

{
    width: 200px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

图片

Of course, for multi-line text , the compatibility is already very good:

{
    width: 200px;
    overflow : hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

图片

Handling dynamic content-protecting boundaries

For some dynamic content, we often use min/max-width or min/max-height to reasonably control the height and width of the container.

There are also some details that need to be considered when using them.

For example, the minimum width of the min-width

.btn {
    ...
    min-width: 120px;
}

图片

When the content is relatively small, it is fine, but when the content is relatively long, problems are prone to occur. I used min-width but didn’t consider the long button:

图片

Here you need to cooperate with padding:

.btn {
    ...
    min-width: 88px;
    padding: 0 16px
}

Borrow Min and Max Width/Height in CSS [2] as an explanation:

图片

0 Content display

This is also a place that is often overlooked.

The page often has list search and list display. So, since there is a normal situation where there is data, of course there will be situations where there are no search results or no content to display in the list.

In this case, we must pay attention to the design of the 0 result page, and also know that this is also a good place to guide users. For the 0 result page, make it clear:

  • data is empty : which may include the user without permission, search results, no results, no data on the page
  • abnormal status : which may include network abnormalities, server abnormalities, load failure waiting

Different situations may correspond to different 0 result pages, with different operation guidance.

For example, the network is abnormal:

图片

Or it is indeed 0 result:

图片

For the 0 result page design, you can read this article in detail: How to design the blank page of the product? [3]

To sum up, the above-mentioned relatively long space has been explaining a truth. developing 1609540e077dc2, one should not only focus on normal phenomena, but also consider various abnormal situations and think comprehensively. Do a good job of handling all possible situations .

Picture related

Pictures should be very common in our business. There are some small details that need attention.

Set the height and width of the picture at the same time

Sometimes it is agreed with the product and design committee that only pictures of a fixed size can be used. Our layout may look like this:

图片

Corresponding layout:

<ul class="g-container">
    <li>
        <img src="http://placehold.it/150x100">
        <p>图片描述</p>
    </li>
</ul>
ul li img {
    width: 150px;
}

Of course, if a picture of an abnormal size appears on the back-end interface, the above unprotected layout will cause problems:

图片

Therefore, for pictures, we always recommend to write height and width at the same time to avoid layout problems caused by wrong picture size:

ul li img {
    width: 150px;
    height: 100px;
}

At the same time, <img> label at the same time, which can occupy the position before the image is loaded, avoiding the rearrangement problem caused by the height and width changes of the image from the unloaded state to the rendered state.

object-fit

Of course, limiting the height and width will also cause problems, for example, the picture is stretched, which is very ugly:

图片

At this time, we can use object-fit , which can specify how the content of the replaceable element (that is, the picture) should adapt to the height and width of its parent container.

ul li img {
    width: 150px;
    height: 100px;
    object-fit: cover;
}

Use object-fit: cover to make the image content fill the entire content frame of the element while maintaining its aspect ratio.

图片

object-fit also has a matching attribute object-position , which can control the position of the picture in its content box. (Similar to background-position ), m defaults to object-position: 50% 50% . If you don't want the picture to be displayed in the center, you can use it to change the actual position of the picture.

ul li img {
    width: 150px;
    height: 100px;
    object-fit: cover;
    object-position: 50% 100%;
}

图片

Like this, object-position: 100% 50% indicates that the picture is displayed from the bottom. Here is a good Demo that can help you understand object-position .

CodePen Demo -- Object position[4]

Consider screen dpr - responsive images

Under normal circumstances, there should be no problems with the display of pictures. But when there are pictures to show, we can do better.

On the mobile terminal or some high-definition PC screens (Apple's MAC Book), the dpr of the screen may be greater than 1. At this time, we may also need to consider using multiple images to adapt to different dpr screens.

It just so happens that the <img> tag provides the corresponding attributes srcset for us to operate.

<img src='photo@1x.png'
   srcset='photo@1x.png 1x,
           photo@2x.png 2x,
           photo@3x.png 3x' 
/>

Of course, this is an older way of writing. srcset adds a new w width descriptor, which needs to sizes , so the better way to write is:

<img 
        src = "photo.png" 
        sizes = “(min-width: 600px) 600px, 300px" 
        srcset = “photo@1x.png 300w,
                       photo@2x.png 600w,
                       photo@3x.png 1200w,
>

Using srcset , we can provide the most suitable pictures for different dpr screens.

There are some concepts mentioned above, dpr, srcset of the picture, and sizes attributes. If you don’t know well, you can move to Front-end basic knowledge overview [5]

Picture is missing

Well, when the picture link is okay, it has been processed. Next, you need to consider what to do when the image link hangs.

There are many ways to deal with it. The best way to deal with it is what I saw in this article by recently-1609540e078289 CSS style handling best practices after image loading failure [6]. Here is a brief introduction:

  1. Use image loading to fail, triggering <img> elements onerror event, failed to load <img> add a new element of style class
  2. Use the newly-added style class to match <img> element to display the default bottom image and at the same time display alt information of the <img> element.
<img src="test.png" alt="图片描述" onerror="this.classList.add('error');">
img.error {
    position: relative;
    display: inline-block;
}

img.error::before {
    content: "";
    /** 定位代码 **/
    background: url(error-default.png);
}

img.error::after {
    content: attr(alt);
    /** 定位代码 **/
}

We use the pseudo-element before to load the default error map, and use the pseudo-element after to display the information of the alt

图片

OK, at this point, even if the complete processing of the picture is complete, you can click here to see the complete Demo:

CodePen Demo - Image processing [7]

Interactive design optimization

The next big part is about the details of some interactions. For interaction design, some general guidelines:

  • Don’t make me think
  • Meet the user's habits and expectations
  • Convenient operation
  • Make proper reminders
  • Don't force users

Transition and animation

In our interaction process, appropriately adds transitions and animations, which can make users perceive the page changes .

For example, loading effects can be seen everywhere on our pages. In fact, it is such an effect that allows users to perceive that the page is loading or processing certain transactions.

图片

Rolling optimization

Scrolling is also a very important part of operating web pages. See what can be optimized:

Smooth rolling: Use scroll-behavior: smooth make rolling silky

Using scroll-behavior: smooth , you can make the scroll box to achieve smooth scrolling instead of sudden jumps. To see the effect, suppose the following structure:

<div class="g-container">
  <nav>
    <a href="#1">1</a>
    <a href="#2">2</a>
    <a href="#3">3</a>
  </nav>
  <div class="scrolling-box">
    <section id="1">First section</section>
    <section id="2">Second section</section>
    <section id="3">Third section</section>
  </div>
</div>

Do not use scroll-behavior: smooth , it is a sudden jump switch:

图片

scroll-behavior: smooth to the scrollable container to achieve smooth scrolling:

{
    scroll-behavior: smooth;
}

图片

Use scroll-snap-type optimize the scrolling effect

sroll-snap-type may be regarded as the core attribute style in the new scrolling specification.

scroll-snap-type[8] : The property defines how a snap point in the scroll container is strictly enforced.

It's a bit difficult to understand just by looking at the definition. Simply put, this attribute specifies whether a container captures the internal scrolling motion, and specifies how to handle the scrolling end state. After the scrolling operation is over, the element stops at a suitable position.

Look at a simple example:

图片

Of course, scroll-snap-type uses, and there are many points that can be controlled and optimized. Due to space limitations, you can’t expand them one by one. For more detailed usage, please see another article of Use sroll-snap-type to optimize scrolling [9]

Control the scroll level to avoid a large number of page rearrangements

This optimization may be a little bit difficult to understand. Need to understand the relevant knowledge of CSS rendering optimization.

Let me talk about the conclusion first. Controlling the scroll level means try to keep the z-index of elements that need CSS animation (either element animation or container scrolling) at the top of the page to avoid unnecessary creation by the browser Graphics layer (GraphicsLayer), can well improve rendering performance .

How do you understand this? One of the factors that triggers the creation of a Graphics Layer layer by an element is:

  • The element has a sibling element with a lower z-index and a composite layer

According to the above points, when we optimize the scrolling performance, we need to pay attention to two points:

  1. By generating an independent GraphicsLayer, using GPU acceleration to improve scrolling performance
  2. If there is no performance problem with scrolling itself, and no independent GraphicsLayer is needed, you should also pay attention to the level of the scroll container to avoid being merged by other elements that created the GraphicsLayer because the level is too high, and passively generate a Graphics Layer, which affects the overall rendering performance of the page

about this, you can read this article - 1609540e08f592 CSS animation techniques and details you don’t know [10]

Click interaction optimization

In terms of user click interaction, there are also some interesting little details.

Optimized gestures - different applications in different scenarios cursor

For different content, it is best to give different cursor styles. CSS natively provides many commonly used gestures.

Using different mouse gestures in different scenarios, conforms to the user's habits and expectations , which can well enhance the user's interactive experience.

First of all, for buttons, there will be at least 3 different cursors, which are clickable and non-clickable. Waiting:

{
    cursor: pointer;    // 可点击
    cursor: not-allowed;    // 不可点击
    cursor: wait;    // loading
}

图片

In addition, there are some common ones. For some input boxes, use cursor: text , for Tips class use cursor: help , zoom in and out pictures zoom-in , zoom-out etc.:

图片

Some commonly used simple columns:

  • Button can be clicked: cursor: pointer
  • The button is forbidden to click: cursor: not-allowed
  • Waiting for Loading status: cursor: wait
  • Input box: cursor: text;
  • The picture viewer can zoom in or out: cursor: zoom-in/ zoom-out
  • Prompt: cursor: help;

Of course, the actual cursor also supports many kinds, you can check it in MDN [11] or the following CodePen Demo here to see the complete list:

CodePen Demo -- Cursor Demo[12]

Click area optimization - pseudo-element expands the click area

The button is a very important part of our web design, and the design of the button is also closely related to the user experience.

Consider a scenario where you are operating the screen on a swaying carriage or with one hand. Sometimes a button can't be touched.

Making it easier for users to click on the button can undoubtedly increase the user experience and improve the accessibility of the page. Especially on the mobile terminal, the buttons are usually very small, but limited by the design draft or the overall UI style, we can’t directly To change the height and width of the button element.

So at this time, is there any way to increase its click hot zone without changing the original size of the button?

Here, the pseudo-element can also represent the mouse interaction event that its host element responds to. With the help of pseudo-elements, it can be easily implemented for us. We can write:

.btn::befoer{
  content:"";
  position:absolute;
  top:-10px;
  right:-10px;
  bottom:-10px;
  left:-10px;
}

Of course, this looks a bit strange on the PC side, but it can get very good results if it is reasonably used on the mobile terminal with a small click area. The effect is as follows:

图片 608782-20160527112625428-906375003

When the pseudo-element of the button has no other purpose, this method is indeed a good point to improve the user experience.

Quick selection optimization - user-select: all

The operating system or browser usually provides some functions for quickly selecting text. Take a look at the following diagram:

图片

Click twice quickly to select a single word, and click three times quickly to select an entire line of content. But if sometimes our core content is divided by separators or hidden in a part of a whole line, it will be more troublesome to select at this time.

With user-select: all , you can wrap the content that needs to be selected once, and the user only needs to click once to select the piece of information:

.g-select-all {
    user-select: all
}

Add the effect of this style to the information that needs to be selected once. This detail is used in some scenes that need to be copied and pasted. It is very easy to use:

图片

CodePen - user-select: all example [13]

Selected style optimization - ::selection

Of course, if you want to go further, CSS also provides a ::selection pseudo-class, which can control the style of the selected text (only color , background , text-shadow ) can be used to further deepen the effect.

图片

CodePen - user-select: all && ::selection control the selected style [14]

Add prohibited selection - user-select: none

If there is a quick choice, there will be its opposite---selection is forbidden.

For some buttons that may be frequently operated, the following awkward scenes may appear:

  • The quick click of the text button triggers the double-click quick selection of the browser, resulting in the text being selected:

图片

  • The quick click of the page turning button triggers the double-click quick selection of the browser:

For this kind of scenario, we need to set the unselectable element to be unselectable. This can be achieved quickly with CSS:

{
    -webkit-user-select: none; /* Safari */
    -ms-user-select: none; /* IE 10 and IE 11 */
    user-select: none; /* Standard syntax */
}

In this way, no matter how fast the click is, there will be no awkward content selection:

图片

Jump optimization

At this stage, Single Page Application (Single Page Application) is widely used, and frameworks such as Vue and React are popular. However, some common writing methods are also prone to give rise to some minor problems.

For example, click a button or text to route the jump. For example, this kind of code often appears:

<template>
    ...
    <button @click="gotoDetail">
        Detail
    </button>
    ...
<template>
...
gotoDetail() {
    this.$router.push({
      name: 'xxxxx',
    });
}

The general logic is to add an event to the button, and after clicking it, jump to another route. Of course, there is no problem with this function itself, but it does not take into account the actual use of the user's scene.

In actual use, because it is a page jump, many times, the user wants to keep the content of the current page and open a new window at the same time. At this time, he will try to click the right mouse button and select to open in a new tab. Page , unfortunately, the above writing method does not support the right mouse button to open a new page.

The reason is that the browser is by reading <a> label href property, to show similar open the page in a new tab this option, for the above wording, the browser is unable to recognize it is a jump link. The simple schematic diagram is as follows:

图片

Therefore, for all routing redirect buttons, it is recommended to use the <a> label, and the built-in href attribute, fill in the redirected routing address. The actual rendered DOM may need to be similar to this:

<a href="/xx/detail">Detail</a>

Ease of use

Ease of use is also a very important link that needs to be considered in interaction design, and there are many things that can be done. Briefly list:

  • Pay attention to the consistency of interface elements and reduce user learning costs
  • Continue the user’s daily usage habits instead of recreating
  • Add some preset values to the drop-down box to reduce the user's filling cost
  • Similar operations are merged together to reduce the cognitive cost of users
  • Give feedback after any operation to let the user know that the operation has taken effect

Explore first, then make a statement

This is very interesting. What does it mean to explore first and then express your stance? That is, we don't force users to do things as soon as they come up, such as logging in.

Consider some examples of common websites:

  • Video sites like Huya, Bilibili, etc., you can watch the experience first, and you will be asked to log in after a certain viewing time (log in to enjoy Blu-ray)
  • E-commerce website, only need to log in when payment is made

The above ease of use and first explore, and then state , part of it comes from: Learn From What Leading Companies A/B Test [15], you can read it carefully.

Font optimization

The choice and use of fonts are actually very particular.

If the website is not mandatory, certain fonts must be used. The latest specification recommends that we use the system default font more. This is the font-family: system-ui keyword in CSS Fonts Module Level 4 - Generic font families [16].

font-family: system-ui can automatically select the default system font under this operating system.

Using the system font of a specific operating system by default can improve performance, because the browser or webview does not have to download any font files, but uses the existing font files. font-family: system-ui font setting is that it matches the font used by the current operating system, and for the text content, it can be displayed most appropriately.

Give two examples, Tmall's font definition and Github's font definition:

  • [17]: font-family: "PingFang SC",miui,system-ui,-apple-system,BlinkMacSystemFont,Helvetica Neue,Helvetica,sans-serif;
  • Github[18]:font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol;

In short, they generally follow this basic principle:

1. Try to use the system default font

The main reason for using the system default font is performance, and the advantage of the system font is that it matches the current operating system, so its text display must be a comfortable display effect.

2. Taking into account both Chinese and Western, Western language first, Chinese second

Chinese or Western (English) must be considered. Since most Chinese fonts also have an English part, but the English part is not very good-looking, but most of the English fonts do not contain Chinese. Usually, the English font declaration is made first, and the best English font is selected, so that it will not affect the selection of Chinese fonts, and the Chinese font declaration is next.

3. Take into account multiple operating systems

Consider multiple operating systems when choosing fonts. For example, many Chinese fonts under MAC OS are not pre-installed in Windows. In order to ensure the experience of MAC users, when defining Chinese fonts, define the Chinese fonts for MAC users first, and then define the Chinese fonts for Windows users;

4. Taking into account the old operating system, ending with the font family serif and sans-serif

When using some very new fonts, consider backward compatibility. Taking into account some extremely old operating systems, using the font family serif and sans-serif endings is always a good choice.

For some of the above fonts, you may be a little -apple-system , such as 0609540e090284, BlinkMacSystemFont . This is because different browser manufacturers have different implementations of the specification. For more details about font definitions, you can read this article - Web The font font-family again 1609540e09028b [19]

Accessibility (A11Y)

Accessibility is a very important part of our website, but most of the front-end (in fact, it should be design, front-end, product) students will ignore it.

I am lurking in a Accessibility Design Group , which includes many accessibility designers and users with certain visual, hearing, and mobility impairments. They often express a point of view in the group, that is, domestic Most of the Web sites and APPs have not considered the use of people with disabilities (or the accessibility is very poor), which is very worrying.

Especially in some of our websites that emphasize interaction and logic, we need to consider the user's usage habits and usage scenarios, and consider from the perspective of high accessibility. For example, if the user does not have a mouse and only uses the keyboard, can we use ours smoothly? website?

Assuming that the user does not have a mouse, this is not necessarily aimed at people with disabilities. In many cases, the user’s hand holding the mouse may be doing other things, such as eating, or doing TO B business, such as supermarket checkout and warehouse receipt. , It is very possible that the user is operating other equipment (scan code gun) and so on with the hand of the mouse.

This article will not specifically elaborate on all aspects of accessibility design, but only from some of the details of accessibility design that I think front-end engineers need to pay attention to and can be done at a small cost. Remember, accessible design for everyone more friendly .

Color contrast

Color is also an attribute we need to deal with every day. For most users with normal vision, the color sensitivity of the page may not be so high. However, for a small number of color-blind and color-blind users, they will be more sensitive to the color of the website, and poor design will cause great inconvenience to them when visiting the website.

What is color contrast

Have you ever cared about the display of page content, and whether the colors used are appropriate? Can users with color weakness and color blindness see the content normally? Good use of color is beneficial at all times, and it is not limited to color weak and color-blind users. When you use your mobile phone outdoors, you can’t see clearly when the sun is strong, and the high-definition, high-contrast text that meets barrier-free standards is easier to read.

There is a concept here- color contrast . Simply put, the description is the difference in brightness between two colors. When applied to our pages, most of the cases are the contrast between the background color (background-color) and the content color (color).

The most authoritative Internet accessibility specification- WCAG AA [20] The specification stipulates that the color contrast of all important content needs to reach 4.5:1 or above (3:1 or above when the font size is larger than 18). Good readability.

Borrow a picture - know almost - 15 recommended UI design tools to help you easily do barrier-free [21]:

图片

Obviously, in the last example above, the text is very unclear, and it is already difficult for normal users to see clearly.

Tool to check color contrast

The Chrome browser has supported checking the color contrast of elements since a long time ago. Take the page I am currently writing as an example, Github Issues edit the two buttons of the page:

图片

Examining the elements, you can see the color contrast of the two buttons respectively:

图片

It can be seen that the color contrast of the white button on the green background is not up to the standard, and it is also marked with a yellow exclamation mark.

In addition, by changing the color in the color picker of the Style interface of the review element, you can also see the current color contrast intuitively:

图片

Focus response

Similar to the homepage of Baidu and Google, after entering the page, the input box will be focused by default:

图片

Not all pages with input boxes need to be focused after entering the page, but focus can let users know very clearly where they are currently and what needs to be done. Especially for users who cannot operate the mouse.

The focusable element on the page is called the focusable element . The focused element will trigger the focus event of the element, and correspondingly, the :focus pseudo-class of the element will be triggered.

Browsers usually use the :focus pseudo-class of the element to add a border to the element to tell the user where the current focused element is.

We can Tab key on the keyboard, and the focus element can tell the user the current focus position :focus

Of course, in addition to the Tab key, for some form pages with multiple input boxes and select boxes, we should also think about how to simplify the user's operation, for example, when the user presses the enter key, it automatically advances to the next field. Generally speaking, the fewer touches a user must perform, the better the experience. :thumbsup:

The screenshot below is completely completed by keyboard operation :

图片

Through the element's :focus pseudo-class and the keyboard Tab key to switch the focus, the user can switch and operate the focus of the page very smoothly without the mouse.

However, in many reset.css , you can often see such a CSS style code, in order to unify the style, eliminate the :focus pseudo-class of focusable elements:

:focus {
    outline: 0;
}

We give the code for the above operation. Also the inclusion of such a code, full keyboard and then click :

图片

Except for the input box, when using Tab to switch the focus to select or button , because there is no :focus , the user will be completely confused and do not know where the focus of the page is now.

Guarantee non-mouse user experience, use :focus-visible

Of course, one reason for the above results is very important. :focus pseudo-class will be triggered as long as the element is focused, regardless of whether the user is using the mouse or the keyboard.

And its own default style is not very acceptable to products or designs, causing many people to change the border color or other methods to replace or directly disable :focus And doing so, from the perspective of accessibility, is undoubtedly disastrous for non-mouse users.

Based on this, in the W3 CSS selectors-4 specification [22], a very interesting :focus-visible pseudo-class has been added.

:focus-visible : This selector can effectively display different forms of focus according to the user's input method (mouse vs keyboard).

With this pseudo-class, it can be done. When the user uses the mouse to operate the focusable element, the :focus not displayed or the performance is weak, and when the user uses the keyboard to operate the focus, use :focus-visible to get the focusable element A strong performance style.

Look at a simple Demo:

<button>Test 1</button>
button:active {
  background: #eee;
}
button:focus {
  outline: 2px solid red;
}

Use the mouse to click:

图片

As you can see, when you click with the mouse, the :active pseudo-class of the element is triggered, and the :focus pseudo-class is also triggered, which is not very beautiful. outline: none is set, the keyboard user experience will be very bad. Try to use the :focus-visible pseudo-class to transform it:

button:active {
  background: #eee;
}
button:focus {
  outline: 2px solid red;
}
button:focus:not(:focus-visible) {
  outline: none;
}

Take a look at the effects, which are clicking the Button with the mouse and clicking the Button with the keyboard to control the focus:

图片

CodePen Demo -- :focus-visible example[23]

As you can see, using the mouse to click will not trigger :foucs outline: 2px solid red will only take effect when the keyboard is operated on the focused element and Tab is used to switch the focus.

In this way, we not only ensure the click experience of normal users, but also the focus management experience of a group of users who cannot use the mouse.

It’s worth noting that some students may wonder why the :not used here instead of writing directly like this:

button:focus {
  outline: unset;
}
button:focus-visible {
  outline: 2px solid red;
}

In order to be compatible with browsers that :focus-visible :focus-visible not compatible, the existence of the :focus

Use WAI-ARIA specification to enhance semantics - div and other non-focus-capable elements simulate focus-capable elements

There is one more point that needs attention.

Many front-end students now like to use non-focus-capable elements to simulate focus-capable elements in the process of front-end development, such as:

  • Use div simulate button elements
  • Use ul simulate drop-down lists select and so on

Many component libraries currently do this, such as element-ui and ant-design.

When using non-focus-capable elements to simulate focus-capable elements, it is important to note that it is not only the appearance that is the same, but also the behavior and performance of the original button and select , which can reflect the element. The semantics of, can be focused, can be switched by Tab, and so on.

Based on a large number of similar scenarios, there is the WAI-ARIA standard [24]. WAI-ARIA is a technical specification that provides barrier-free access to dynamic and interactive Web content for people with disabilities.

Simply put, it provides some attributes to enhance the semantics and behavior of tags:

  • You can use the tabindex attribute to control whether the element can be focused, and whether/where it participates in sequential keyboard navigation
  • You can use the role attribute to identify the semantics and functions of the element. For example, use <div id="saveChanges" tabindex="0" role="button">Save</div> to simulate a button
  • There are also a large number of aria-* attributes, which represent the attributes or states of the elements, helping us to further identify and realize the semantics of the elements, and optimize the accessibility experience

Use tools to view the semantics of tags

Let's take a look at how a button is defined on the Github page. Take the Edit button on the Github Issues page as an example:

图片

This piece clearly describes some features related to the accessibility of this button, such as Contrast color contrast. The description of the button, which is Name , is for screen readers. The Role logo is the attribute of this element. It is A button, Keyboard focusable , indicates whether it can be captured by the Tab button of the keyboard.

Analyze buttons simulated using non-focusable elements

Here, I randomly selected a scene in our business that uses the span simulation button, which is a breadcrumb navigation, click to jump to it, and found it terrible:

图片

HTML code:

<span class="ssc-breadcrumb-item-link"> Inbound </span>

图片 image

Basically, the accessibility is 0. As a button, it cannot be focused or selected by keyboard users. It has no specific semantics. The color contrast is too low and may not be visible to visually impaired users. And, as a button that can jump to the page, it has no tags other a and no attributes of href

Even for breadcrumb navigation, we can not transform it into <a> tags, but we need to do some accessibility transformations of most basic

<span role="button" aria-label="goto inbound page" tabindex="0" class="ssc-breadcrumb-item-link"> Inbound </span>

Don’t forget to change the color again to reach above the minimum color contrast, and then take a look:

图片

OK, in this way, a button that is the most basic and meets the minimum accessibility requirements is barely up to standard. Of course, this button can be further modified, involving more in-depth accessibility knowledge, this article will not go into depth.

Analysis component library A11Y

Finally, in our more commonly used Vue- element-ui [25], React- ant-design [26], let's take a look at some of the functions related to ant-design in improving accessibility.

Taking the Select component as an example, ant-design uses a lot of WAI-ARIA attributes, so that the drop-down box simulated by div not only conforms to a drop-down box in terms of performance, but also conforms to a drop-down box in terms of semantics and behavior. It is simple one example:

图片

Take a look at the DOM part of the div that simulates the drop-down box:

图片

Take a look at the interactive experience:

图片

The above operations are all done under the keyboard, which looks unremarkable. In fact, while the component library normally responds to the switch of the focusable elements, it adds a lot of keyboard event responses to the div-simulated select. You can use enter, up and down Key etc. to select the available options. In fact, a lot of work has been done.

For A11Y-related content, the length and content are very large, and this article cannot be expanded one by one. If you are interested, you can read through the following articles:

  • WAI-ARIA basics[27]
  • WAI-ARIA 1.1[28]
  • Focus management in the Web [29]
  • Accessibility features [30]
  • 71 Design Points to Improve the Web User Experience [31]
  • -Accessibility Design Team [32]

in conclusion

From the page shows , interaction details , accessibility three major aspects, a list of some of some useful experience in the actual development process, accumulated. Although not comprehensive enough, from the beginning, I didn't think about the big and comprehensive, mainly some points that may be useful but easy to be overlooked, and it can be regarded as a good guide for checking deficiencies.

Of course, many of these are my personal opinions. There may be some problems in understanding, and some concepts are not well understood. I hope you can help me point out.

At last

This concludes this article, I hope it helps you :)

If you have any questions or suggestions, you can exchange more, original articles, limited writing style, and lack of knowledge. If there are any irregularities in the article, please let me know.

Reference


兰俊秋雨
5.1k 声望3.5k 粉丝

基于大前端端技术的一些探索反思总结及讨论