How to trigger the :active pseudoclass on keyboard 'enter' press? (using only 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 with ENTER or SPACE
  • Holding down SPACE on a button will show the :active style (except for FireFox; this looks like FF bug since it works OK for mousedown)
  • Holding down ENTER on a button will repeatedly trigger onclick every time your keyboard sends the character.
  • Holding down SPACE on a button will trigger onclick only if the SPACE 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.)
  • Hyperlinks can be activated with ENTER only.
  • Clicking on hyperlinks will show :active style, using ENTER (or touch) will not.

document.getElementById('t1').focus(); // set focus for easier demo
:active
{
   color: Red;
}
<input type='text' id='t1' value='Set focus and hit tab'/>
<a href='javascript:;' onclick='console.log("Hyperlink")'>Hyperlink</a>
<input type='button' value='Button' onclick='console.log("Button")'/>

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:

a:hover .class,
a:focus .class { 
  background-color: rgba(243,113,89, 0.95); 
}