Loading
CSS Pseudo-class
What is a Pseudo-Class in CSS ?

In CSS, pseudo-classes allow you to apply styles to elements based on their state, position, or interaction without adding extra classes or IDs. Pseudo-classes begin with a colon (:) and are attached to selectors.



Syntax:

selector:pseudo-class {
  property: value;
}



Commonly Used Pseudo-Classes

pseudo-classDescription
:activeIt is used to add style to an active element.
:hoverIt adds special effects to an element when the user moves the mouse pointer over the element.
:linkIt adds style to the unvisited link.
:visitedIt adds style to a visited link.
:langIt is used to define a language to use in a specified element.
:focusIt selects the element which is focused by the user currently.
:first-childIt adds special effects to an element, which is the first child or another element.



1. :hover – Style on Mouse Hover

The :hover pseudo-class applies a style when a user places their mouse pointer over an element. It's commonly used for links, buttons, or interactive elements.


Example:

<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      text-align: center;
    }

    h1:hover {
      color: red;
    }

    h2:hover {
      color: blue;
    }
  </style>
</head>

<body>
  <h1>Hello World</h1>
  <h2>This is an example of :hover pseudo-class</h2>
</body>

</html>

Output:

Uploaded Image




2. :active – Style on Click

The :active pseudo-class is triggered while an element is being clicked (like a button or link). It helps provide feedback during interaction.


Example:

<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      text-align: center;
    }

    a:active {
      color: yellow;
    }

    h1, h2, h3 {
      color: red;
    }
  </style>
</head>

<body>
  <h1>Hello World</h1>
  <h2>The :active pseudo-class</h2>
  <h3>Click the following link to see the effect</h3>
  <a href="#">Click the link</a>
</body>

</html>

Output:

Uploaded Image




Key Point

  • Pseudo-classes enhance interactivity and style dynamically.
  • No need to add extra HTML attributes or JavaScript.
  • Common examples: :hover, :active, :focus, :visited, :first-child, :nth-child().