What are CSS pseudo-classes

CSS pseudo-classes are used to add special effects to some selectors. You do not need to use JavaScript or any other script to use those effects. They allow you to style elements based on their state, position, or user interaction.

Syntax

selector:pseudo-class {
    property: value;
}

Common Pseudo-classes

The most commonly used pseudo-classes are −

Value Description
:link Use this class to add special style to an unvisited link.
:visited Use this class to add special style to a visited link.
:hover Use this class to add special style to an element when you mouse over it.
:active Use this class to add special style to an active element.
:focus Use this class to add special style to an element while the element has focus.
:first-child Use this class to add special style to an element that is the first child of some other element.
:lang Use this class to specify a language to use in a specified element.

Example: Link States

The following example demonstrates different link states using pseudo-classes −

<!DOCTYPE html>
<html>
<head>
<style>
    a:link {
        color: blue;
        text-decoration: none;
    }
    
    a:visited {
        color: purple;
    }
    
    a:hover {
        color: red;
        text-decoration: underline;
    }
    
    a:active {
        color: orange;
    }
</style>
</head>
<body>
    <p><a href="https://example.com">Hover over this link</a></p>
    <p><a href="visited-link.html">This link changes when visited</a></p>
</body>
</html>
Links appear in blue initially, turn purple when visited, red when hovered, and orange when clicked.

Example: First Child Pseudo-class

The :first-child pseudo-class selects the first child element −

<!DOCTYPE html>
<html>
<head>
<style>
    p:first-child {
        color: red;
        font-weight: bold;
    }
    
    li:first-child {
        background-color: yellow;
        padding: 5px;
    }
</style>
</head>
<body>
    <div>
        <p>First paragraph (styled)</p>
        <p>Second paragraph (normal)</p>
        
        <ul>
            <li>First item (highlighted)</li>
            <li>Second item (normal)</li>
            <li>Third item (normal)</li>
        </ul>
    </div>
</body>
</html>
The first paragraph appears in bold red text. The first list item has a yellow background with padding.

Conclusion

CSS pseudo-classes provide a powerful way to style elements based on their state or position without using JavaScript. They enhance user experience by creating interactive and dynamic styling effects.

Updated on: 2026-03-15T11:25:32+05:30

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements