Skip to content
Velloreth
Web Development 8 min read

CSS Pseudo-Classes: A Practical Guide

Pseudo-classes select elements by state or position. Learn :hover, :focus-visible, :nth-child, :has, and the ones that matter most.

By

What pseudo-classes are

A pseudo-class selects elements based on state or position, written with a single colon.

a:hover { color: blue; }        /* state */
li:first-child { font-weight: bold; } /* position */
input:disabled { opacity: 0.5; }      /* state */

The distinction from pseudo-elements: a pseudo-class selects an existing element in a particular state; a pseudo-element (::before) creates a part that does not exist in the DOM.

Interaction states

:hover

Matches when the pointer is over the element.

.button:hover {
  background: #1d4ed8;
}

On touch devices, :hover may never fire or may stick after a tap. Never put essential information behind :hover.

:active

Matches while the element is being activated, such as during a mouse press.

.button:active {
  transform: translateY(1px);
}

:focus

Matches when the element has focus.

input:focus {
  border-color: #2563eb;
}

:focus-visible

The modern way to style focus. It matches only when the browser determines focus should be visible, which is usually keyboard navigation.

.button:focus-visible {
  outline: 2px solid #2563eb;
  outline-offset: 2px;
}

The benefit: a mouse click does not show the ring, but a Tab press does. This is what users expect.

:focus-within

Matches when the element or any descendant has focus. Useful for highlighting a form group.

.field:focus-within {
  border-color: #2563eb;
  box-shadow: 0 0 0 3px rgb(37 99 235 / 0.1);
}

Form states

input:disabled { opacity: 0.5; cursor: not-allowed; }
input:enabled { }
input:checked { }
input:required { }
input:optional { }
input:valid { border-color: green; }
input:invalid { border-color: red; }
input:placeholder-shown { }
input:read-only { }

:placeholder-shown is useful for floating labels, because it matches only while the placeholder is visible — that is, while the field is empty.

.field:has(input:placeholder-shown) label {
  transform: translateY(0);
}

:invalid fires immediately on page load for empty required fields, which is why it is often paired with :user-invalid (which fires only after interaction) where supported.

Structural pseudo-classes

:first-child, :last-child, :only-child

li:first-child { margin-top: 0; }
li:last-child { margin-bottom: 0; }
p:only-child { margin: 0; }

:nth-child

1-based indexing, with formula support.

li:nth-child(2) { }        /* the second */
li:nth-child(odd) { }      /* 1st, 3rd, 5th */
li:nth-child(even) { }     /* 2nd, 4th, 6th */
li:nth-child(3n) { }       /* every third */
li:nth-child(3n+1) { }     /* 1st, 4th, 7th */
li:nth-child(-n+3) { }     /* the first three */

The formula an+b means: start at b, step by a.

FormulaMatches
2nEven positions
2n+1Odd positions
3nEvery third
-n+3First three
n+4Fourth onward

:nth-of-type

Like :nth-child, but counts only elements of the same type.

/* The second <p>, ignoring other elements */
p:nth-of-type(2) { }

This is the fix when :nth-child gives unexpected results because of mixed element types.

:not()

Excludes elements.

li:not(:last-child) {
  border-bottom: 1px solid #e5e7eb;
}

This is the idiomatic way to add separators between items without a trailing one.

:is() and :where()

Group selectors without repeating the rest.

/* Instead of h1:hover, h2:hover, h3:hover */
:is(h1, h2, h3):hover { }

/* :where() has zero specificity */
:where(h1, h2, h3) { margin-block: 0; }

:has()

Matches an element that contains a matching descendant. This is the parent selector.

/* Style a card that contains an image */
.card:has(img) {
  padding: 0;
}

/* Style a form group whose input is invalid */
.field:has(input:invalid) {
  border-color: red;
}

/* Style a label whose checkbox is checked */
label:has(input:checked) {
  font-weight: bold;
}

:has() removes the need for JavaScript in many cases. It is supported in all modern browsers.

a:link { }      /* unvisited */
a:visited { }   /* visited */
a:hover { }
a:active { }
a:focus-visible { }

Order matters, because the specificity is equal and later rules win. The traditional mnemonic is LVHA: link, visited, hover, active.

a:link { color: #2563eb; }
a:visited { color: #7c3aed; }
a:hover { color: #1d4ed8; }
a:active { color: #1e40af; }

Note that :visited styles are heavily restricted for privacy reasons — only colour-related properties apply.

Accessibility

Never remove focus outlines

/* Wrong: makes the page unusable by keyboard */
*:focus { outline: none; }

/* Right: a visible custom ring */
:focus-visible {
  outline: 2px solid #2563eb;
  outline-offset: 2px;
}

The focus ring is how keyboard users know where they are. Removing it without a replacement is one of the most common accessibility failures.

Do not rely on :hover alone

/* Wrong: the information is unreachable on touch */
.tooltip { display: none; }
.trigger:hover .tooltip { display: block; }

/* Right: also respond to focus */
.trigger:hover .tooltip,
.trigger:focus-visible .tooltip { display: block; }

Adding :focus-visible makes the interaction keyboard-accessible.

Use :focus-within for groups

.field:focus-within {
  outline: 2px solid #2563eb;
}

This highlights the whole field group when any part has focus, which helps users track their position.

Combining pseudo-classes

Pseudo-classes chain, and the combination is often more useful than either alone.

/* A required field that is currently invalid */
input:required:invalid {
  border-color: #dc2626;
}

/* A link that is hovered and not disabled */
a:hover:not([aria-disabled='true']) {
  text-decoration: underline;
}

/* The last item, unless it is the only item */
li:last-child:not(:only-child) {
  border-bottom: none;
}

The order in the chain does not matter for matching, but it does affect readability. Put the structural pseudo-class first and the state pseudo-class last, which reads as “this element, in this state”.

A common pattern is combining :not() with a state to exclude a case:

.button:not(:disabled):hover {
  background: #1d4ed8;
}

Without the :not(:disabled), a disabled button would still show a hover effect, which is misleading.

Pseudo-classes and specificity

Each pseudo-class adds to the class part of the specificity score, except :where(), which adds nothing.

a:hover { }              /* 0,0,1,1 */
a:focus-visible { }      /* 0,0,1,1 */
:where(a):hover { }      /* 0,0,1,0 */
:is(a, button):hover { } /* 0,0,1,1 — takes the most specific argument */

This matters when you are trying to override a state style. A rule with two pseudo-classes is harder to override than one with a single class, which is why :where() is useful for resets and defaults.

/* A reset that is easy to override */
:where(a) {
  color: inherit;
  text-decoration: none;
}

Because :where() contributes zero specificity, any later rule with a class will override it without needing !important.

Pseudo-classes for state you cannot see

Some pseudo-classes match conditions that are invisible in the markup, which makes them useful for progressive enhancement.

/* The user has not interacted with the field yet */
input:user-invalid {
  border-color: #dc2626;
}

/* The element is being targeted by the URL fragment */
section:target {
  background: #fef3c7;
}

/* The element is in fullscreen mode */
video:fullscreen {
  width: 100vw;
  height: 100vh;
}

/* The element is being printed */
@media print {
  a:not([href^='#'])::after {
    content: ' (' attr(href) ')';
  }
}

:target is particularly useful for documentation and table-of-contents links, because it highlights the section the user jumped to without any JavaScript.

:user-invalid is the modern replacement for :invalid in forms. :invalid fires immediately on page load for an empty required field, which shows an error before the user has typed anything. :user-invalid fires only after the user has interacted and left the field, which is the behaviour people expect.

Pseudo-classes and progressive enhancement

A useful property of pseudo-classes is that an unsupported one invalidates only its own rule, not the whole stylesheet. This makes them safe to use ahead of full support.

/* Browsers that do not support :has() ignore this rule entirely */
.card:has(img) {
  padding: 0;
}

The card keeps its default padding in older browsers, which is a graceful fallback. This is different from a syntax error, which can invalidate a whole rule block.

The practical approach: write the base style first, then add the enhancement with the newer pseudo-class. The base style is the fallback, and the enhancement is a bonus.

.card {
  padding: 1rem; /* works everywhere */
}

.card:has(img) {
  padding: 0; /* enhancement */
}

Practical guidance

  • Use :focus-visible for focus rings, not :focus.
  • Never remove focus outlines without a visible replacement.
  • Pair :hover with :focus-visible for keyboard access.
  • Use :not(:last-child) for separators.
  • Use :nth-of-type when element types are mixed.
  • Use :has() to style parents based on children.
  • Use :where() for resets, since it has zero specificity.
  • Remember LVHA order for link states.

For the related guides, see css-specificity-explained and html-semantic-elements-guide. For the broader context, css-custom-properties and css-animations-basics.

Quotable summary

A pseudo-class selects elements based on state or position, written with a single colon, such as :hover for a hovered element or :nth-child(2) for the second child. :focus-visible is the modern way to style keyboard focus, showing the ring only when the browser determines focus should be visible, which is usually keyboard navigation. :nth-child uses 1-based indexing and supports formulas like 2n+1 for odd elements and -n+3 for the first three. :has() lets you style a parent based on its children, which removes the need for JavaScript in many cases. Never remove focus outlines without providing a visible replacement, because it makes the page unusable by keyboard, and always pair :hover with :focus-visible so interactions work without a mouse.

Frequently asked questions

What is a pseudo-class?
A pseudo-class selects elements based on their state or position in the document, such as :hover for a hovered element or :first-child for the first child. It is written with a single colon.
What is the difference between a pseudo-class and a pseudo-element?
A pseudo-class selects an existing element in a particular state, using one colon. A pseudo-element creates a part of an element that does not exist in the DOM, such as ::before, using two colons.
What is the difference between :focus and :focus-visible?
:focus matches whenever an element has focus, including after a mouse click. :focus-visible matches only when the browser determines focus should be visible, which is usually keyboard navigation. Use :focus-visible for focus rings.
How does :nth-child work?
:nth-child(n) matches the nth child, counting from 1. It accepts formulas: 2n for even, 2n+1 for odd, 3n for every third, and -n+3 for the first three.
What does :has() do?
:has() matches an element that contains a matching descendant, so you can style a parent based on its children. For example, .card:has(img) styles cards that contain an image.
Should I remove the focus outline?
Never remove it without a replacement. The focus ring is how keyboard users know where they are. If the default is unattractive, style :focus-visible with a custom ring rather than removing it.