:focus-visible
Usually we provide :focus
styles for interactive elements to enhance (keyboard) accessibility. But when we click around with mouses, most browsers will activate :focus
state of elements like <button>
. This will easily cause misunderstanding that the button is “selected” especially when different types of buttons are placed together. The draft of CSS Selector Level 4 provided a :focus-visible
pseudo class selector to help us targeting focused elements more accurately.
Actually Chrome is handling native <button>
s in a similar way by default.
Usage
VEUI's default style package veui-theme-one uses a polyfill library for :focus-visible
to provide optimized interactive experience. You need to import it yourself in your application code:
import 'focus-visible'
Technically focus-visible isn't really a “polyfill” because we have to use the .focus-visible
selector instead of directly using :focus-visible
. This should also be noted when customizing styles.
Browser compatibility
As the polyfill provided by WICG won't automatically import other polyfills, you need to import polyfill for classList
when you need to support IE9 (requires to be installed by yourself as well).
$ npm i --save classlist-polyfill
import 'classlist-polyfill'
Demo
After including the polyfill, :focus
styles are applied both with mouse clicks and keyboard activation, while .focus-visible
styles are only applied with keyboard activation.
This example is only for demonstration purpose and doesn't reflect ONE DESIGN's styles. Please note that our polyfill for :focus-visible
works differently in Firefox and Safari. Clicking a button in these browsers won't set the :focus
state on the button.
<template>
<article>
<button>:focus</button> <button class="special">
.focus-visible
</button>
</article>
</template>
<style lang="less" scoped>
button {
&:focus {
outline: 2px solid #eee;
}
}
.special {
&:focus {
outline: none;
}
&.focus-visible {
outline: 2px solid #eee;
}
}
</style>