:hover

Term side of the Card.
Topic: Pseudo Classes
Unit title: :hover
Categories: Pseudo-class
Explanation side of the Card

Explanation: The pseudo-class that applies styles to an element when the user moves the mouse pointer over it. It's commonly used for interactive elements like buttons or links, changing their appearance to indicate they are clickable or to highlight them.

Browser compatibility:
  • The chrome browser supports this feature starting from version 1.
  • The edge browser supports this feature starting from version 12.
  • The firefox browser supports this feature starting from version 1.
  • The safari browser supports this feature starting from version 2.
Availability: 

Example

Wrongcss
.card:hover {
  transform: translateY(-4px);
}
Rightcss
@media (hover: hover) {
  .card:hover {
    transform: translateY(-4px);
  }
}
.card:focus-visible {
  outline: 2px solid;
}

The media query limits the lift to real pointers, and :focus-visible gives keyboard users a visible state too.

Common mistakes

  • A button stays highlighted after a tap on a phone because of a sticky :hover state.
  • Hiding important actions until hover, so touch and keyboard users never find them.

Key points

  • Hover-only effects sit inside @media (hover: hover) so taps don't leave them stuck.
  • Every :hover style has a matching :focus-visible style for keyboard users.
  • Content shown on hover, like menus, can also be opened by click or keyboard.

Interview questions

Does :hover work on mobile?

Partly. A tap often triggers :hover, and it can stay until the user taps elsewhere.

How do I make a hover effect also work for keyboard users?

Group the selectors: .btn:hover, .btn:focus-visible { ... }.

Can :hover be used on any element?

Yes. :hover works on any element, not just links and buttons.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy