Input fields adding focus-visible on click
Asked Answered
N

1

8

I am attempting to selectively apply an outline on an input field only when the user has navigated to the element by keyboard. From my understanding the way to do this is removing the outline on focus but applying on focus-visible like so:

input:focus {
  outline: 2px solid transparent;
}

input:focus-visible {
  outline: 2px solid;
}
<input type="text">

However from what I can tell an input element registers a click and keyboard selection equally. I would like to override this somehow. I am using Chrome but have tested with Safari as well.

Thanks in advance for your help!

Ninurta answered 27/4, 2023 at 17:8 Comment(0)
F
2

The behaviour you are seeing is as expected (and desirable).

You want all users (whether on mobile, tablet or desktop using a mouse or keyboard) to have focus indicators on inputs when they are active.

The time when focus-visible is relevant is for things like links on mobile. It is often not desirable to have a focus indicator show when you click a link on a mobile. (even though whether it should show or not is debatable).

So for an <input> you should just use input:focus{} and reserve :focus-visible for links (and a few other specific use cases such as <button> elements that result in focus being changed to another element).

Falsity answered 28/4, 2023 at 9:55 Comment(2)
Thank you for your reply. Are there any exceptions? Specifically I have noticed that many search inputs I have used do not have outlines.Ninurta
Not that I can think of. Search inputs without outlines are not following accessibility best practices. Bear in mind 96%+ of websites have accessibility errors, so you can't really rely on other sites for guidance I am afraid as the odds are they are making mistakes. Hope that helps!Falsity

© 2022 - 2024 — McMap. All rights reserved.