We have some buttons, which are styled with css and have some icons like this:
This button has as default outline property, so that everytime we click on it, it has an outline (in chrome blue):
to get rid of it, we can of course overwrite this property like:
outline: none
but then when we tab through and reach this button, it will also not have any outline, which is a bad practice for accesibility.
Can we achive this so that this outline appears only when we come on this button with tab, but not when we click on it?
Just as info: We have also some a tags which seems visually just like that, and with a tags we have exact this behaviour we want, outlines appear only when we tab on to that link, but not on click. We just want to have exact same behaviour with button tags also.
If you want to remove the focus around a button, you can use the CSS outline property. You need to set the “none” value of the outline property.
The tabindex attribute assigns a tab sequence number to an button. The actual tabindex numbers are not important.
The outline button style removes all background images or colors from a button and gives it a lighter look. The outline style buttons can be used for various purposes, for example: Indicating the secondary action complementing the primary action.
Use a semi-colon to separate the different style elements in the HTML button tag. Type color: in the quotation marks after "style=". This element is used to change the text color in the button. You can place style elements in any order in the quotation markers after "style=".
When you click on an element it casts :active
on it, so you want to chain :active
and :focus
together:
button:active:focus {
outline: none;
}
<button>Button</button>
As you said this doesnt work with additional css, in this case you have to implement a bit complicated solution, where you add class to body when user uses tab for a first time, otherwise you remove outlines all together
function handleFirstTab(e) {
if (e.keyCode === 9) { // the "I am a keyboard user" key
document.body.classList.add('user-is-tabbing');
window.removeEventListener('keydown', handleFirstTab);
}
}
window.addEventListener('keydown', handleFirstTab);
body:not(.user-is-tabbing) button:focus {
outline: none;
}
button {
background-color: red;
}
<button>Button</button>
Can we achive this so that this outline appears only when we come on this button with tab, but not when we click on it?
Yes you can by using :focus-visible
.
If you want an outline to appear when button is tabbed and not clicked, set outline: none
on the button on :focus
but not on :focus-visible
:
button:focus:not(:focus-visible) {
outline: none;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With