:hover vs :focus

2019-08-16

 | 

~2 min read

 | 

317 words

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



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!