Home > front end >  Accessibility: extending browser default focus styles to custom widgets
Accessibility: extending browser default focus styles to custom widgets

Time:07-25

We have a few accessible components which are created using divs/spans aria properties. When these custom inputs / widgets get focus, we would like to show a focus state. We rely on browser default focus styles for that.

The problem is that browser default focus styles work with interactive elements like button, a, etc, but not with div, span by default.

Is there a way to extend browser default outline styles to these custom components ?

Things I have considered:

  • override the default browser style, and define a custom focus style for everything
  • figure out the browsers i want to support and somehow copy / recreate the existing focus styles and apply with browser prefix in the css

CodePudding user response:

I believe your issue lies elsewhere. Probably some of your stylesheets change the default browser outlines.

You can reset them to browser defaults by using the CSS revert property:

/* some reset stylesheet might contain something like this */
span:focus, div:focus {
  outline: none;
}

/* which you can reset for your custom controls */
[role=button]:focus, [role=link]:focus {
  outline: revert;
}
<!-- Use <button> wherever possible! -->
<div tabindex="0" role="button" onclick="" onkeydown="">Custom Button</div>

<!-- Use <a> instead, whenever possible! -->
<span tabindex="0" role="link" onclick="" onkeydown="">Custom Link</span>

I believe this is the case because browsers’ default CSS does style any element’s focus:

Chrome’s Default Focus Styles

:focus { 
    outline: auto 5px -webkit-focus-ring-color
}

Firefox’ Default Focus Styles

/* focusable content: anything w/ tabindex >=0 is focusable */
…, div:focus, …, span:focus {
  /* Don't specify the outline-color, we should always use initial value. */
   outline: 1px dotted;
}
  • Related