Pseudo-classes in Css


A CSS Pseudo-Class is a keyword added to a selector which specifies a special state of the selected elements.

You can use it to style an element based on its state, position, or user interaction (hover, active, visited, etc.) without adding a class or id.

 

selector:pseudo-class {
  property: value;
} 

css-pseudo-classes


Commonly Used Pseudo-Classes

Pseudo-Class Description
:hover When the user hovers over an element
:active When an element is activated (e.g., clicked)
:focus When an element (like input) is focused
:visited Links the user has visited
:link Unvisited links
:first-child First child of its parent
:last-child Last child of its parent
:nth-child(n) Matches the nth child
:not(selector) Selects elements not matching the selector
:checked Checkbox or radio button that is checked
:disabled Disabled form elements
:enabled Enabled form elements
:empty Elements with no children (including text)

Examples of Pseudo-Classes

:hover

a:hover {
  color: red;
} 

Changes link color to red when hovered.

 


:active

button:active {
  background-color: green;
} 

Button background turns green when clicked.


:focus

input:focus {
  border: 2px solid blue;
}

Input gets a blue border when focused (clicked or tabbed).


:visited and :link

a:link {
  color: blue;
}

a:visited {
  color: purple;
}

Link is blue if unvisited, purple if visited.


:first-child and :last-child

p:first-child {
  color: crimson;
}

li:last-child {
  font-weight: bold;
}

The first <p> child in a parent gets crimson color.

The last list item becomes bold.


Example

<!DOCTYPE html>
<html>
<head>
  <style>
    a:hover {
      color: red;
    }

    input:focus {
      border: 2px solid blue;
    }

    li:first-child {
      color: green;
    }

    li:last-child {
      font-weight: bold;
    }
  </style>
</head>
<body>

<a href="#">Hover over me</a><br><br>

<input type="text" placeholder="Click to focus"><br><br>

<ul>
  <li>First item</li>
  <li>Second item</li>
  <li>Last item</li>
</ul>

</body>
</html> 

Benefits of Pseudo-Classes

  • No need to add extra HTML classes or IDs.
  • Dynamically style elements based on user interaction, state, or position.
  • Great for improving UX (User Experience).



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.