CodeBlanks Logo Icon CodeBlanks

:hover and :focus

CSS course · Intermediate · Lesson 13/98

Learn :hover and :focus pseudo-classes.

What is :hover?

A pseudo-class captures a specific state of an element. The best known is :hover: it activates when the mouse pointer is over an element.

For example, with a:hover { color: red; } on a menu link, the moment the user moves the mouse over the link, its text turns red. Move the mouse away and the style disappears. This gives the page instant feedback.

What is :focus?

:focus matches an element while it has focus. When you tab into an input field or reach a link with the keyboard, that element is focused.

Visualizing focus is essential for accessibility: keyboard users must see where they are. With input:focus { outline: 2px solid #0066cc; }, the focused field gets a clear border.

Interaction states of links

A link goes through several interaction states during its life. CSS gives each one its own pseudo-class:

  • :link — not yet visited
  • :visited — already visited
  • :hover — pointer over it
  • :active — moment of click
  • :focus — keyboard focus

Order matters; the LVHA order (link, visited, hover, active) keeps conflicts clean.

Exercise Write interaction styles for a link and an input

Write an a:hover selector and add color: darkred inside it. Then write an input:focus selector and add outline: 2px solid #0066cc inside it. Both declarations should sit in their own { } block.

Show example solution
/* add link and input styles */
a:hover {
  color: darkred;
}
input:focus {
  outline: 2px solid #0066cc;
}

Test yourself

  1. When does the :hover pseudo-class activate?

    a:hover {
      color: darkred;
      text-decoration: underline;
    }
    • The moment the link is clicked
    • When the pointer moves over the link
    • As soon as the page loads
    • After the link has been visited
    Show answer

    When the pointer moves over the link — Correct. :hover matches while the pointer is over the element.

  2. Complete the selector for a focused link

    a____ {
      outline: 2px solid #0066cc;
    }
    Show answer
    a:focus {
      outline: 2px solid #0066cc;
    }
  3. Match each pseudo-class to its state

    :hover
    Pointer over it
    :focus
    Keyboard focus
    :visited
    Already visited
    :active
    Moment of click

All lessons in Intermediate