Common Pseudo-classes: hover, focus, active

What a Pseudo-class Is

A pseudo-class selects an element based on a state or condition that is not represented directly in the HTML markup - such as whether the mouse is currently over it, or whether it currently has keyboard focus.

:hover

.btn:hover {
  background: #1d4ed8;
}

Applies while a pointer is positioned over the element. On touch devices, hover has no real equivalent, so interactive elements should never rely on hover alone to reveal essential content or actions.

:focus

.btn:focus {
  outline: 2px solid #1d4ed8;
}

Applies while an element has keyboard focus - after being tabbed to, or clicked. Removing the default focus outline without replacing it with something equally visible is a common accessibility mistake, since keyboard users then lose track of where they are on the page.

:active

.btn:active {
  transform: translateY(1px);
}

Applies only during the moment an element is actively being clicked or tapped - useful for giving buttons a satisfying "pressed" feel.

Combining States Together

.btn:hover,
.btn:focus {
  background: #1d4ed8;
}

It is common to share styles between :hover and :focus so that keyboard users get the same visual feedback that mouse users see on hover.

A Note on Order

When several of these pseudo-classes are defined for the same element, their order in the stylesheet can matter if they have equal specificity - a common convention is :hover, then :focus, then :active, so each later state can still override the one before it.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.