🎨

Understanding CSS Pseudo-classes

Apr 24, 2025

CSS Pseudo-classes

Introduction

CSS pseudo-classes are used to define a special state of an element. They allow you to style elements based on their state, such as when a user hovers over them or when they have been visited. Pseudo-classes can be particularly useful for enhancing the interactivity and accessibility of web pages.

Key Uses of Pseudo-classes

  • Mouse Interaction: Style elements when the user interacts with them, e.g., hovering over a link.
  • Link States: Differentiate between visited and unvisited links.
  • Focus States: Style elements when they gain focus.
  • Form Elements: Style valid, invalid, required, or optional form elements.

Syntax

selector:pseudo-class { property: value; }

Common Anchor Pseudo-classes

Example

a:link { color: #FF0000; } /* Unvisited link */ a:visited { color: #00FF00; } /* Visited link */ a:hover { color: #FF00FF; } /* Mouse over link */ a:active { color: #0000FF; } /* Selected link */
  • Note: a:hover must follow a:link and a:visited; a:active must follow a:hover for correct styling.

Pseudo-classes with HTML Classes

  • Pseudo-classes can be combined with HTML classes for more specific styling.
  • Example: Change the color of a link with the class highlight when hovered. a.highlight:hover { color: #ff0000; }

Hover on <div> Elements

  • Pseudo-classes like :hover can be applied to other elements such as <div>.
  • Example: Change the background color of a <div> on hover.

div:hover { background-color: blue; }

## Tooltip Hover Example - Use `:hover` to display elements like tooltips. - **Example**: Display a `<p>` element when hovering over a `<div>`. ```css p { display: none; background-color: yellow; padding: 20px; } div:hover p { display: block; }

The :first-child Pseudo-class

  • Matches the first child of a parent element.
  • Example: Style the first <p> element in a parent.

p:first-child { color: blue; }

- More complex selectors can be used to target specific child elements within parents. ## The `:lang` Pseudo-class - Allows for language-specific styling. - **Example**: Style quotes in paragraphs with Norwegian language. ```css q:lang(no) { quotes: "~" "~"; }

Exploring More Examples

  • Additional examples can be found on the W3Schools website, including focus styles and hyperlink styling.

CSS Pseudo-classes Reference

  • A comprehensive list of CSS pseudo-classes is available for further learning and exploration.
  • Visit the CSS Pseudo-classes Reference for more details.