The CSS:
a:focus { opacity: .75 }
a:active { transform: translateY(4px) }
The intent:
Keyboard users tab to the link, using the
:focus
style as a visual cueThey hit
enter
to activate the link; the:active
style gives visual keypress feedback
The problem:
The :active
style triggers properly for a mouse click, but not a keypress. Can I fix this with just CSS?
Good question!
Yeah, you can't do this anymore.
A long time ago MSIE treated
:active
like:focus
so there was sort of a way to accomplish this with hyperlinks (this was before gigabit internet speeds and when browsers didn't do a good job of showing load-in-progress except for a dumb waving flag or something).Run the below Snippet to see the behavior in action:
input type='button'
can be activated withENTER
orSPACE
SPACE
on a button will show the:active
style (except for FireFox; this looks like FF bug since it works OK for mousedown)ENTER
on a button will repeatedly triggeronclick
every time your keyboard sends the character.SPACE
on a button will triggeronclick
only if theSPACE
key is released while still focused on the button. (For example, you can simulate mouse click this way: tab to a button, hold down space, then hit tab again and release it to cancel the click.)ENTER
only.:active
style, usingENTER
(or touch) will not.So you are stuck using JavaScript or a plugin like Flash / Silverlight for this.
:focus will be the state entered when the keyboard user tabs to that element. Note that tabbing will cycle through the link tags on your page, so any css styling must be applied with the selector a:focus.
:active will be the state entered when the user hits the enter button on their keyboard.
Here's a little snippet of an example of how to apply css for both keyboard and mouse users:
You can absolutely get
:focus
to work with keyboard, however active would be bit difficult.:focus
is applied when that element receives focus. Like, when user clicks an input field by mouse or selects that input field by tab. Here is an example that shows how focus work; both with tab and mouse. W3School Focus For more info MDN :focusHowever
:active
is bit different. it gets applied in the timeline between user clicking the mouse button and releasing it. This is hard to achieve using keyboard. Because there is no press and hold for enter key. The moment user presses the enter button, link will open up. Here you can see the example on how:active
works. W3School Active For more info MDN :activeIf you are going to use the pseudo-classes for links, then I would suggest using
:focus
, it will do the trick for both mouse and tab key.