SyntaxStudy
Sign Up
CSS Pseudo-Class Selectors
CSS Beginner 6 min read

Pseudo-Class Selectors

Pseudo-Class Selectors

Pseudo-classes select elements based on their state or position in the document tree. They are prefixed with a single colon (:).

User-Action Pseudo-Classes

:hover activates when the pointer is over an element. :focus activates when an element receives keyboard or mouse focus. :active fires during a click.

Structural Pseudo-Classes

:first-child, :last-child, :nth-child(n), and :nth-of-type(n) select elements by their position among siblings. :not(selector) negates a selector.

Form-State Pseudo-Classes

:checked, :disabled, :required, :valid, and :invalid reflect the current state of form controls.

Example
/* Hover state */
.btn:hover {
    background-color: #1557b0;
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0,0,0,.2);
}

/* Focus for accessibility */
a:focus-visible {
    outline: 3px solid #fbbc04;
    outline-offset: 2px;
}

/* Zebra striping with nth-child */
tr:nth-child(even) {
    background-color: #f5f5f5;
}

/* First paragraph after a heading */
h2 + p:first-of-type {
    font-size: 1.1rem;
}

/* Invalid input highlight */
input:invalid {
    border-color: #d32f2f;
    background: #ffebee;
}

/* Everything except the active nav item */
.nav-link:not(.active) {
    color: #555;
}
Pro Tip

Prefer :focus-visible over :focus for styling keyboard focus rings — it suppresses the ring for mouse clicks while keeping it for keyboard users.