CSS Advanced Selectors

CSS Pseudo Classes

CSS Pseudo Classes are used to define a special state of an HTML element.

They allow you to style elements based on:

  • User interaction
  • Element position
  • Form state
  • Dynamic conditions

Pseudo classes start with a colon (:) and are widely used to create interactive and responsive user interfaces.

Common examples include:

  • :hover
  • :focus
  • :first-child
  • :last-child
  • :nth-child()

Syntax

CSS Pseudo Classes Syntax

css

selector:pseudo-class {
    property: value;
}

CSS Pseudo Classes Example

css

a:hover {
    color: red;
}

Changes the link color when the mouse pointer hovers over it.

Attributes

Pseudo ClassDescriptionExample
:hoverStyles an element when hovereda:hover
:focusStyles an element when focusedinput:focus
:first-childSelects the first child elementp:first-child
:last-childSelects the last child elementp:last-child
:nth-child()Selects a specific childli:nth-child(2)

Example

CSS Pseudo Classes Complete Example

html

<!DOCTYPE html>
<html>
<head>
    <title>CSS Pseudo Classes Example</title>
    <style>
        a:hover {
            color: red;
        }
        input:focus {
            border: 2px solid blue;
            outline: none;
        }
        li:first-child {
            color: green;
            font-weight: bold;
        }
        li:last-child {
            color: orange;
        }
        li:nth-child(2) {
            color: purple;
        }
    </style>
</head>
<body>
    <a href="#">Hover over this link</a>
    <br><br>
    <input type="text" placeholder="Click here">
    <br><br>
    <ul>
        <li>HTML</li>
        <li>CSS</li>
        <li>JavaScript</li>
        <li>React</li>
    </ul>
</body>
</html>

Output

Browser Output

css

The link will turn red when hovered
The input field will show a blue border when focused
The first list item (HTML) will appear in green
The second list item (CSS) will appear in purple
The last list item (React) will appear in orange

Browser Support

Chrome
Edge
Firefox
Safari
Opera
IE
YesYesYesYesYesYes

Notes

  • Pseudo classes are dynamic and respond to user actions.
  • :hover is commonly used for buttons, links, and menus.
  • :focus improves accessibility and form usability.
  • :nth-child() supports formulas.

Example:

nth-child Formula Example

css

li:nth-child(odd) {
    background-color: #f5f5f5;
}

Styles all odd-numbered list items.

Popular Pseudo Classes

Pseudo ClassUse Case
:hoverMouse interaction
:focusActive form field
:activeClicked element
:first-childFirst item in a group
:last-childLast item in a group
:nth-child()Specific item selection

Conclusion

CSS Pseudo Classes allow you to style elements based on their state, position, or user interaction. They are essential for creating interactive, accessible, and visually engaging websites without using JavaScript.