Skip to main content

Interactive Pseudo-classes

These pseudo-classes style elements according to how the user interacts with them.


Pseudo-classes Used on Links

Links commonly rely on four pseudo-classes: :link for unvisited links, :visited for visited ones, :hover for a mouse over the link, and :active for an activated link.

Example

The link color here depends on the link's state.

Note: For a:hover to work, it MUST follow a:link and a:visited in the CSS. For a:active to work, it MUST follow a:hover. Case does not matter in pseudo-class names.

Prompt
Display links in different colors depending on their state. Use a:link (red #FF0000), a:visited (green #00FF00), a:hover (magenta #FF00FF), and a:active (blue #0000FF). Include a sample link to demonstrate.
Output: complete HTML page

:hover on <div>

Links are not the only elements that respond to :hover; other elements can use it too.

Example

Prompt
Demonstrate the :hover pseudo-class on a div element. When the user hovers over the div, change its background-color to blue. The div should have some text content and initial styling to make the hover effect visible.
Output: complete HTML page

:focus on <input>

An element that receives focus, for instance an input field a user clicks on or tabs to, can be styled through the :focus pseudo-class.

Example

Prompt
Demonstrate the :focus pseudo-class on an input field. When the input receives focus, change its background-color to yellow. Include a label and input field.
Output: complete HTML page

Pseudo-classes and HTML Classes

Combining pseudo-classes with HTML classes is easy.

Example

Here :hover applies only to the <a> element with class "highlight".

Prompt
Combine a pseudo-class with an HTML class. Use the selector a.highlight:hover to change the color to red (#ff0000) when hovering over links with class "highlight". Include both a regular link and a highlight link to show the difference.
Output: complete HTML page

Simple Tooltip Hover

A simple tooltip effect needs only :hover: a hidden element appears when the user hovers over its parent.

Example

A <p> element shows up, like a tooltip, on hovering over a <div> element.

Prompt
Create a simple tooltip effect using :hover. A paragraph is hidden by default (display: none) with a yellow background and 20px padding. When the user hovers over the parent div, the paragraph becomes visible (display: block). The div text says "Hover over me to show the p element."
Output: complete HTML page