Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 139 ยท Selectors

Pseudo-classes

Learn the CSS pseudo-classes that style elements by state, including hover, focus, focus-visible, checked, disabled, form validity, :user-invalid, :target, :empty and :root.

Some things about an element aren't written in the HTML at all. Is the mouse over it right now? Does it have keyboard focus? Is that checkbox ticked? Is the email in this field valid? The answers change from moment to moment as people use the page.

Pseudo-classes let you style elements based on that kind of state. They start with a single colon and attach to any selector, like a class the browser adds and removes for you: a:hover, input:focus, .option:checked. This lesson covers the state-based pseudo-classes you'll use most: interaction, form state, validity and a few document-level ones. Position-based ones like :first-child get their own lesson, Structural Pseudo-classes.

How pseudo-classes attach

A pseudo-class is written right after the selector it qualifies, with no space:

CSS
button:hover { โ€ฆ }        /* a button that is hovered */
.card:hover .title { โ€ฆ }  /* a .title inside a hovered .card */

The space matters. button:hover means "a button in the hover state". button :hover (with a space) means "any hovered element inside a button": a descendant combinator followed by a pseudo-class on the universal selector.

Each pseudo-class counts like a class in specificity, so a:hover is (0, 1, 1).

User interaction: :hover, :active and :focus

  • :hover matches while a pointer is over the element (or any of its descendants).
  • :active matches while the element is being activated: from mouse-down until release, or while a key is pressing a button.
  • :focus matches the element that currently has focus: the field you are typing in, or the link you tabbed to.
Hover, active and focus

Touchscreens don't really hover. A tap usually triggers :hover until you tap elsewhere, so never hide essential content or actions behind hover alone.

:focus-visible: focus rings where they help

Plain :focus matches whenever an element has focus, including after a mouse click on a button. Many designers disliked the ring appearing on click and removed outlines entirely, which made sites unusable from the keyboard.

:focus-visible solves this. The browser matches it only when it decides a focus indicator is helpful: typically when focus arrives from the keyboard, and always for text fields. Mouse clicks on buttons and links usually don't trigger it.

CSS
.btn:focus-visible {
  outline: 3px solid #f59e0b;
  outline-offset: 3px;
}
Click vs Tab with :focus-visible

Never write outline: none for focus without providing a clearly visible alternative. Keyboard users rely on the focus indicator to know where they are. See Outlines for more on designing good focus styles.

  • :link matches links (<a> with an href) that haven't been visited.
  • :visited matches links to pages in the browser's history.

For privacy, browsers severely limit :visited. Only color-related properties (such as color, background-color and border-color) can change, and scripts can't read the result. Otherwise a page could detect which sites you have visited. If you style link states, the traditional order is :link, :visited, :hover, :active, so that later states override earlier ones at equal specificity.

Form state: :checked, :disabled, :enabled, :required, :optional

Form controls expose their state through pseudo-classes:

Pseudo-class Matches
:checked checked checkboxes and radio buttons, and selected <option>s
:disabled / :enabled controls that are disabled / not disabled
:required / :optional controls with / without the required attribute
:read-only / :read-write fields that can't / can be edited
:placeholder-shown inputs currently showing their placeholder

Unlike attribute selectors, these reflect the live state. :checked updates the instant someone clicks, even though the checked attribute in the markup never changes.

Live form state

The :has() in that example selects a label based on what it contains. It is covered in :is(), :where(), :not() and :has().

Validity: :valid, :invalid and :user-invalid

Browsers validate form fields using attributes like required, type="email", min and pattern (see Form Validation). CSS can show the result:

  • :valid and :invalid match fields that currently pass or fail their constraints.
  • :in-range and :out-of-range match number and date inputs relative to min and max.

The problem with :invalid is timing. An empty required field is invalid from the moment the page loads, so styling :invalid in red shouts at people before they've typed anything.

:user-invalid fixes that. It matches only after the user has interacted with the field (typically after changing it and moving away, or trying to submit). It's supported in all current major browsers; there is a matching :user-valid too.

:invalid vs :user-invalid

Document-level pseudo-classes: :target, :root and :empty

:target matches the element whose id matches the URL fragment. After someone follows a link to #faq, the element with id="faq" is the target. It's a handy way to highlight the section a reader just jumped to:

CSS
section:target {
  background: #fef9c3;
  scroll-margin-top: 80px;
}

:root matches the document's root element, which is <html> in a web page. It's the conventional home for global custom properties:

CSS
:root {
  --brand: #4f46e5;
  --radius: 8px;
}

:root behaves like html but has the specificity of a class.

:empty matches elements with no children at all: no elements and no text, not even whitespace. (Comments are allowed.) It's useful for hiding empty containers that would otherwise show padding or borders:

Hiding empty boxes with :empty

The last badge contains a single space, so it isn't empty and stays visible. That catches people out when templates add whitespace.

Combining pseudo-classes

You can chain pseudo-classes, and mix them with classes and combinators:

CSS
.btn:hover:not(:disabled) { โ€ฆ }
input:required:user-invalid { โ€ฆ }
.card:hover .card-title { โ€ฆ }
.toggle:checked + .panel { โ€ฆ }

The last two show a powerful pattern: the state of one element styles another. A hovered card restyles its title; a checked toggle shows the panel after it.

More state pseudo-classes

A handful of less famous pseudo-classes solve specific problems neatly. You'll reach for them less often, but when you need one, nothing else does the job as well.

Pseudo-class Matches
:any-link every link with an href, visited or not
:placeholder-shown an input or textarea while its placeholder is visible
:read-only / :read-write elements the user can't / can edit
:indeterminate checkboxes in the "mixed" state, unchecked radio groups, and <progress> without a value
:lang() elements in a given language, including inherited languages
:autofill inputs the browser has filled in automatically

:any-link is shorthand for :link, :visited. It matches <a> and <area> elements that have an href, so a:any-link styles real links while skipping placeholder anchors such as <a>Coming soon</a>.

:placeholder-shown matches while a field is empty and showing its placeholder. That makes it the key to the floating label pattern: a label sits inside the field like a placeholder, then moves up once the user types. Give the input a placeholder of a single space so the pseudo-class has something to track.

:read-only and :read-write describe whether the user can edit an element. Be careful with :read-only on its own: every element that isn't editable matches it, including headings and paragraphs. Always attach it to a field selector, as in input:read-only. Contrast that with :disabled: a read-only field can still be focused, selected, copied and submitted, while a disabled one can't.

:indeterminate matches a checkbox whose indeterminate property has been set by JavaScript (there's no HTML attribute for it), the radio buttons of a group where none is selected, and a <progress> element with no value. The "mixed" checkbox is common in "select all" controls when only some items are selected.

:lang() matches elements by language, based on the lang attribute of the element or any ancestor. :lang(fr) also matches regional variants such as fr-CA. That makes it more reliable than an attribute selector like [lang="fr"], which only matches the element that carries the attribute.

Here are the first five together:

Floating labels, mixed checkboxes and more

Type into the City field: the label stays small and up after you leave the field, because the placeholder is no longer shown. The French line uses lang="fr-CA", yet :lang(fr) matches it. Click the checkbox and its italic "mixed" style disappears, since clicking clears the indeterminate state.

:autofill matches inputs whose value the browser filled in from saved addresses or passwords. Browsers paint autofilled fields with their own background color, and in Chromium that color can't be overridden with background-color, because the browser's style wins. A common workaround is a large inset shadow, which covers the background:

CSS
input:autofill {
  box-shadow: 0 0 0 100px #eef2ff inset;  /* paints over the browser's yellow or blue */
  -webkit-text-fill-color: #0f172a;
}

The unprefixed :autofill has worked in all major browsers since 2023; older WebKit and Chromium versions only knew :-webkit-autofill. Autofill can't be triggered inside this site's sandboxed editors, which is why this one is shown as a read-only example.

Form pseudo-classes in practice

The table above names each form pseudo-class once. Real forms mix several of them, and a few details decide whether your styles behave. Here is the practical guide.

:in-range and :out-of-range

These two look at the min and max attributes of <input type="number">, range, date, month, week, time and datetime-local. A value inside the limits matches :in-range, and a value outside matches :out-of-range. Two rules are worth remembering:

  • They only apply to inputs that have a min or max. An input with neither matches neither pseudo-class.
  • An empty field is not out of range. It matches :in-range, so use :required or :placeholder-shown if you also care about "nothing typed yet".

The browser validates range on typing, so :out-of-range also makes the field :invalid. Use :out-of-range when you want a message about the specific rule, such as "pick one to six tickets", and :invalid for general errors.

:required, :optional and the label

:required and :optional select the field, but the thing people read is the label. With :has() the label can react to the field it contains:

CSS
label:has(:required) .name::after { content: " *"; color: #b91c1c; }
label:has(:optional) .name::after { content: " (optional)"; color: #64748b; }

That keeps the star in one place instead of being hard-coded into every label, and it disappears automatically when the required attribute is removed.

:read-only is not :disabled

:read-only and :disabled look similar and behave differently:

readonly field disabled field
Can receive focus Yes No
Text can be selected and copied Yes Depends on the browser
Sent with the form Yes No
Matches :read-only Yes Yes (it isn't editable)
Matches :read-write No No

Because a disabled control also matches :read-only, write input:read-only:enabled if you want to style only fields that are read-only on purpose.

The "select all" checkbox

A parent checkbox that stands for a group needs a third state, "some are checked". There is no HTML attribute for that, so JavaScript sets the indeterminate property, and CSS reacts with :indeterminate. Browsers draw a dash by default, and you can add your own cue. Clicking the box clears the state, so recalculate it whenever a child changes.

Range, required, read-only and indeterminate together

Change the ticket count to 9 and the field turns red and shows its hint; set it to 4 and the border is green again. Tick one extra and "All extras" shows the amber "(some selected)" note, tick all three and it becomes fully checked. The read-only booking reference is dashed, while the disabled seat only fades, because input:read-only:enabled skips it. Notice that the label rules say input:optional and input:read-only, not the bare pseudo-classes: a plain <span> is not editable, so a bare :read-only matches it and the "(optional)" marker would never appear.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is :focus-visible usually better than :focus for focus rings on buttons?

    The browser matches :focus-visible when a visible indicator is useful, which keeps keyboard users oriented without rings on every click.
  2. 2. An empty required email field is on the page. Which pseudo-class does it match before the user touches it?

    The field fails its constraint immediately, so it matches :invalid. :user-invalid waits for the user to interact.
  3. 3. What is the difference between a:hover and a :hover?

    Without a space, the pseudo-class qualifies the a. With a space, it becomes a descendant selector.
  4. 4. Which element matches p:empty?

    :empty requires no child elements and no text at all, not even a space.
  5. 5. Why can :visited only change a few color properties?

    Browsers limit :visited styling for privacy, so layout and scripts cannot reveal your browsing history.

Summary

  • Pseudo-classes style elements by state, written with one colon right after a selector.
  • :hover, :active and :focus follow user interaction; :focus-visible shows focus rings when they help.
  • :link and :visited style links; :visited is restricted to colors for privacy.
  • :checked, :disabled, :required and friends reflect live form state.
  • :valid/:invalid match immediately; :user-invalid/:user-valid wait for interaction.
  • :in-range/:out-of-range need a min or max, and an empty field counts as in range; :read-only also matches disabled fields and non-editable elements, so pair it with input and :enabled.
  • :target matches the URL fragment's element, :root is the <html> element, and :empty matches truly empty elements.

Next: Structural Pseudo-classes โ€” selecting elements by their position, from :first-child to :nth-child().