DEV Community

Stephen Charles Weiss
Stephen Charles Weiss

Posted on • Originally published at stephencharlesweiss.com on

:hover Vs :focus

Most of the time, these two pseudo-selectors act in concert. In fact, they’re so frequently triggered together that my naive testing approach couldn’t differentiate them this morning.

So what’s the difference? From the W3 spec:

  • The :hover pseudo-class applies while the user designates an element with a pointing device, but does not necessarily activate it. For example, a visual user agent could apply this pseudo-class when the cursor (mouse pointer) hovers over a box generated by the element. User agents that do not support interactive media do not have to support this pseudo-class. Some conforming user agents that support interactive media may not be able to support this pseudo-class (e.g., a pen device that does not detect hovering).
  • The :active pseudo-class applies while an element is being activated by the user. For example, between the times the user presses the mouse button and releases it. On systems with more than one mouse button, :active applies only to the primary or primary activation button (typically the “left” mouse button), and any aliases thereof.
  • The :focus pseudo-class applies while an element has the focus (accepts keyboard or mouse events, or other forms of input).

Hover requires a pointer device without activating while focus can be achieved with keyboard events.

A few examples helped clarify situations where these two states can diverge:

  1. A form element which a user selects, and then moves the mouse elsewhere. In that case, focus is true while hover is false.
  2. A keyboard user tabbing through a page can make elements active without hovering.

An interesting aside from the spec:

Note: If the ‘ :hover ’ state applies to an element because its child is designated by a pointing device, then it’s possible for ‘ :hover ’ to apply to an element that is not underneath the pointing device.

Footnotes

Top comments (1)

Collapse
 
kelvinzhao profile image
Kelvin Zhao

The problem is why the hover state is activated on focus. =(