4
votes

So I've noticed that if I create my own focus styles for (for example) a button, the styling will show after I've clicked the button with a mouse. But when I click a button with default focus styling, there is no outline.

However, you can perfectly tab through the buttons and both of them will show an outline when in focus.

I'm very curious of why default focus styling and my own focus styling does not function in the same way. Why does both appear on keyboard navigation, but only one of them appear on mouse click?

Please try out both clicking and navigating with keyboard on these buttons:

button {
  padding: .5rem;
  margin: 2rem;
}

.my-button:focus {
  outline: 3px solid red;
}
<button type="button">
  This button has default focus styling
</button>

<button type="button" class="my-button">
  This button has my own focus styling
</button>

PS: I'm not interested in any javascript hacky solutions, or removing the focus styling in any way. I just want to learn why the web works this way.

2
This is only true in some browsers.BoltClock

2 Answers

1
votes

Chrome uses outline-style: auto

This is defined by CSS specs as follow:

The auto value permits the user agent to render a custom outline style, typically a style which is either a user interface default for the platform, or perhaps a style that is richer than can be described in detail in CSS, e.g. a rounded edge outline with semi-translucent outer pixels that appears to glow. As such, this specification does not define how the outline-color is incorporated or used (if at all) when rendering auto style outlines. User agents may treat auto as solid.

This means that not all browsers consider that solid and auto are the same.

And you can reproduce the same behaviour as Chrome using the auto value rather than solid:

button {
  padding: .5rem;
  margin: 2rem;
}

.my-button:focus {
  outline: 3px auto red;
}
<button type="button">
  This button has default focus styling
</button>

<button type="button" class="my-button">
  This button has my own focus styling
</button>
0
votes

By default, the outline property is an accessibility tool for keyboard users. Using the mouse, the cursor is your visual aid to know what element has the focus. Tabbing through a screen filled with elements without an outline visible will cause the user to lose track of where he has tabbed to (this is why you should never remove the outline completely).