State Pseudo-Classes: Links, :hover, :focus-visible, :target and Form States
Pseudo-classes that react to state: :link, :visited and its privacy limits, :target, :hover and :active on touch screens, :focus-visible and :focus-within, form states from :checked to :user-invalid, :open, :popover-open and :modal, media states, and :lang() and :dir().
kvi5hnuCode Sprout team member14 min readOn this page
Structural pseudo-classes depend on where an element sits. The ones in this article depend on state: whether a link has been visited, whether the pointer is over an element, which element has keyboard focus, whether a checkbox is checked or a field is invalid, whether a dialog is open. The browser tracks these states and updates the matching styles as they change, with no script needed.
Link pseudo-classes
| Pseudo-class | Matches |
|---|---|
:link | a link (<a> or <area> with an href) whose URL the user hasn't visited |
:visited | a link whose URL is in the browser's history |
:any-link | any link, visited or not |
These match only real links. A plain a { } rule also matches <a> elements without an href, which some code uses as placeholders, so :any-link (or a:link, a:visited) is the precise way to style links:
a:any-link { color: #8a3b12; }
a:visited { color: #6b4a8a; }
Why :visited is so limited
If any style could depend on :visited, a page could render a list of links and check, with a script or layout tricks, which ones the visitor has been to, revealing their browsing history. To prevent that, browsers apply strict rules to :visited:
- Only color properties apply:
color,background-color,border-color(and its sides),outline-color,column-rule-color,text-decoration-color,text-emphasis-color, and the fill and stroke of SVG. Anything else in a:visitedrule is ignored: you can't change size, font weight or background images. - The color must already exist. A
:visitedrule can only change a color that the link already has a non-transparent value for. To give visited links a background, set abackground-colorona(or:link) first, then change it in:visited. - The alpha channel can't change. A
:visitedcolor is used with the opacity of the unvisited color, so you can't make visited links transparent. - Scripts can't see the difference.
querySelectorAll(":visited")returns no elements, andgetComputedStyle()on a visited link returns the unvisited styles. - Some browsers partition history, so a link only shows as visited if it was visited from the same site.
Within those limits, distinguishing visited links is still worth doing on content-heavy sites, such as search results and article lists, where people need to know what they've already read.
:target
When the URL has a fragment, as in https://harborbooks.example/events#poetry-night, the element with id="poetry-night" is the target, and matches :target. It's a simple way to highlight the section a link jumped to:
:target {
outline: 3px solid #f4c95d;
scroll-margin-top: 5rem; /* leave room for a sticky header (article 57) */
}
Clicking another fragment link changes the target. If the fragment doesn't match any element, nothing is :target.
:target-within, which would match ancestors of the target, was dropped from the specification and isn't supported. Use :has(:target) instead: section:has(:target) matches the section containing the target. :target-current is a newer pseudo-class for scroll markers in CSS carousels (article 115).
User action pseudo-classes
| Pseudo-class | Matches an element that... |
|---|---|
:hover | is under the mouse pointer, or contains the element that is |
:active | is being activated: from mouse-button press to release, or while touched |
:focus | has keyboard focus |
:focus-visible | has focus, and the browser thinks the focus should be shown |
:focus-within | has focus, or contains the element that has focus |
They work on any element, not just links: .book-card:hover, input:focus, form:focus-within.
:hover and touch screens
Touch screens have no hover. When you tap an element, mobile browsers usually apply :hover briefly or until you tap elsewhere, which can leave an element stuck in its hover style. So:
- Never hide essential content or actions behind hover. A menu that appears only on hover is unreachable on a phone, and for keyboard users.
- Use the
hovermedia feature to apply hover effects only on devices with a real hover, such as a mouse or trackpad (article 76):
@media (hover: hover) {
.book-card:hover { transform: translateY(-2px); }
}
A hover style that changes the element's size, such as a bigger font or a thicker border, can make the page reflow under the pointer, which may then leave the element and end the hover. Prefer changes that don't affect layout, such as color, shadow, outline or transform.
Order: link, visited, focus, hover, active
When several states apply at once, and the rules have the same specificity, the later rule wins (article 17). That's why link styles are traditionally written in this order:
a:link { color: #8a3b12; }
a:visited { color: #6b4a8a; }
a:focus-visible { outline: 2px solid currentColor; }
a:hover { color: #b85a22; }
a:active { color: #4d1f08; }
A hovered link is also :link or :visited, so :hover must come after them to win. An active link is usually hovered too, so :active comes last. Put :hover first and it would never show on visited links. The mnemonic is "LoVe HAte", with focus fitted in before hover.
:focus, :focus-visible and :focus-within
:focus matches whichever element has focus, however it got there: by keyboard, mouse click, touch, or a script calling .focus().
:focus-visible matches only when the browser decides that a focus indicator is useful. The browsers' rules are similar:
- After keyboard navigation (
Tab, arrow keys), any focused element matches. - Text fields match whenever they're focused, even after a mouse click, since you need to see where you're typing.
- Buttons and links clicked with a mouse don't match.
- When a script moves focus, the element matches if the previous focused element was showing a focus indicator, so keyboard users keep seeing it.
That makes :focus-visible the right place for focus rings: keyboard users always see where they are, and mouse users don't see rings on every button they click. The browser's default focus styles already use :focus-visible. Article 42 covers designing them.
:focus-within matches an element when it, or anything inside it, has focus. It's useful for highlighting a whole form field group, or keeping a dropdown open while focus is inside it:
form { font-family: system-ui, sans-serif; display: grid; gap: 0.75rem; max-width: 22rem; }
.field { padding: 0.5rem; border: 2px solid transparent; border-radius: 8px; }
.field:focus-within { border-color: #f4c95d; background: #fffbea; }
input { font: inherit; width: 100%; box-sizing: border-box; }
button { font: inherit; padding: 0.4rem 1rem; }
button:focus-visible { outline: 3px solid #8a3b12; outline-offset: 2px; }
Click in the field: its group turns yellow. Click the button with the mouse: no ring. Press Tab to reach it with the keyboard: the ring appears.

One focused input makes every ancestor match :focus-within, so the form and the field group both react, while the other group doesn't.
Form state pseudo-classes
Form controls expose many states. All of these work on <input>, <select>, <textarea> and <button> as appropriate, and some on <option>, <fieldset> and <form>:
| Pseudo-class | Matches a control that... |
|---|---|
:enabled, :disabled | can be used, or has disabled (directly or from a disabled <fieldset>) |
:checked | is a checked checkbox or radio button, or a selected <option> |
:indeterminate | is a checkbox whose indeterminate property a script set, a radio group with nothing selected, or a <progress> without a value |
:default | is the default: the option or checkbox checked in the HTML, or a form's default submit button |
:required, :optional | has, or doesn't have, the required attribute |
:valid, :invalid | meets, or fails, its constraints (required, type, pattern, min, max, step, length) |
:user-valid, :user-invalid | is valid or invalid, but only after the user has interacted with it |
:in-range, :out-of-range | has a value inside, or outside, its min/max |
:placeholder-shown | is currently showing its placeholder text, which means it's empty |
:autofill | was filled in by the browser's autofill |
:read-only, :read-write | can't, or can, be edited by the user. contenteditable elements are :read-write |
:blank | (not supported yet) would match empty inputs |
Some details that trip people up:
:checkedfollows the live state. It updates as the user clicks, unlike the[checked]attribute selector, which reflects only the HTML.:invalidapplies immediately. A required field is invalid the moment the page loads, before the user has typed anything, so styling:invalidin red shows errors on an untouched form.:user-invalidwaits until the user has changed the field and left it, or tried to submit the form. It's almost always what you want for error styles.- An empty optional field is
:valid, even if it's an email field: no value is a valid value when nothing is required. - A value can be
:in-rangeand:invalidat once, for example 25 in a field withmin="0" max="100" step="10". :read-onlymatches most elements, including every<p>and<div>, because they can't be edited. Combine it with a control selector, as ininput:read-only.- Browsers' autofill styles (usually a yellow or blue background) are hard to override. You can add styles to
:autofill, but replacing the background color reliably is still a known problem.

Two results stand out: :invalid already marks two fields as errors on a form nobody has touched, which is why error styles belong on :user-invalid, and :read-only matches the checkboxes and the disabled field as well as the readonly one.
form { font-family: system-ui, sans-serif; display: grid; gap: 0.6rem; max-width: 20rem; }
input { font: inherit; padding: 0.35rem; border: 2px solid #999; border-radius: 6px; }
input:required { border-left-width: 6px; }
input:user-invalid { border-color: #b3261e; background: #fdecea; }
input:user-valid { border-color: #2f7d4f; }
input:placeholder-shown { font-style: italic; }
label:has(+ input:required)::after { content: " *"; color: #b3261e; }
Nothing is red at first. Type an invalid address and press Tab: the field turns red. Type 9 in the number field and leave it: it's out of range, so it turns red too.
:has() lets a label react to its field's state, as in the asterisk rule above (article 12).
Open and top-layer states
| Pseudo-class | Matches |
|---|---|
:open | an open <details> or <dialog>, a <select> with its picker shown, an <input> with a picker open (such as a date picker) |
:popover-open | an element with the popover attribute while it's shown |
:modal | a dialog opened with showModal(), or an element in fullscreen that blocks the rest of the page |
:fullscreen | an element in fullscreen mode |
:picture-in-picture | a video playing in picture-in-picture (Baseline since July 2026) |
details:open > summary { font-weight: 700; }
[popover]:popover-open { animation: fade-in 0.2s; }
details:open replaces the older details[open], which reflects the attribute rather than the state, though both work for <details>. Article 60 covers popovers and dialogs in depth.
Media playback states
Audio and video elements have state pseudo-classes too: :playing, :paused, :seeking, :buffering, :stalled, :muted and :volume-locked. They let custom controls react without a script:
.player:has(video:paused) .play-icon { display: block; }
Safari has supported them since 2022 and Firefox since April 2026, and Chrome 158 completed the set on November 17, 2026, so they're Baseline newly available. Chrome 157 and earlier treat a selector such as video:playing as invalid, so keep such rules separate from others.
Language and direction
:lang()
:lang() matches elements by their language, which is usually inherited: a paragraph inside <html lang="fr"> is French even though it has no lang attribute of its own. That makes it more accurate than the [lang|="fr"] attribute selector, which only looks at the element's own attribute.
:lang(fr) q { quotes: "« " " »"; }
:lang(de), :lang(nl) { hyphens: auto; }
:lang(en) matches en, en-GB and en-US. Selectors Level 4 also allows a list, :lang(de, nl), and wildcard ranges such as :lang("*-CH") for any language as used in Switzerland. Firefox and Safari support both, but Chromium doesn't: there, the selector is invalid and the whole rule is dropped. Use separate :lang() selectors, or wrap them in :is(), until Chromium catches up.
:dir()
:dir(rtl) and :dir(ltr) match elements by their text direction, as determined by HTML: the dir attribute, inherited from ancestors, or detected from the content with dir="auto". They don't look at the CSS direction property.
.next-icon:dir(rtl) { transform: scaleX(-1); } /* flip arrows in right-to-left text */
Unlike [dir="rtl"], :dir() works for elements that inherit their direction. It has been supported in all browsers since late 2023. In many cases, logical properties such as margin-inline-start make direction-specific rules unnecessary (article 47).
Other state pseudo-classes
:definedmatches elements the browser knows: every built-in element, and custom elements once their class is registered.book-card:not(:defined) { visibility: hidden; }hides a component until its script loads (article 14).:scopematches the element a query is relative to. Inelement.querySelectorAll(":scope > li"), it's that element, and inside@scopeit's the scope root (article 22). In a normal stylesheet, it's the same as:root.:active-view-transitionmatches the root element while a view transition is running (article 114).:state(name)matches custom elements in a custom state (article 14).
What's current
:user-validand:user-invalidare Baseline widely available since May 2026.:openis Baseline newly available since May 2026, when Safari 26.5 added it. Use[open]for<details>and<dialog>if you support older browsers.:popover-openis Baseline newly available since April 2024.:autofillworks in all current browsers, though Firefox's support is partial.- Media pseudo-classes (
:playing,:pausedand the rest) became Baseline newly available in November 2026, with Chrome 158. :lang()with a list or wildcards works in Firefox and Safari, not in Chromium.:local-link,:target-withinand:blankaren't supported in any browser.
Common questions
Why doesn't this rule work?
a:visited { font-weight: bold; }
For privacy, :visited rules can only change colors. Every other property in them is ignored, so the history can't be detected through layout.
Why does my hover effect stay on after tapping on a phone?
Touch browsers emulate hover on tap, and keep it until you tap elsewhere. Wrap hover effects in @media (hover: hover) so they apply only to devices with a real pointer.
Should I remove the focus outline because it looks ugly when clicking buttons?
No. Style :focus-visible instead of :focus, and the ring appears only when it's useful, mainly for keyboard users. Removing focus indicators entirely makes the page unusable without a mouse, and fails accessibility requirements.
Why are my required fields red as soon as the page loads?
They're :invalid from the start, because they're empty. Use :user-invalid, which applies only after the user has interacted with the field or tried to submit.
My hover styles don't apply in the right order. What's wrong?
Rules for states with equal specificity are decided by order. Write :link, :visited, :focus/:focus-visible, :hover and :active in that order, so the later, more specific situations win.
What's the difference between :lang(fr) and [lang|="fr"]?
:lang() uses the element's actual language, including what it inherits from ancestors and the document. The attribute selector only matches elements that have the lang attribute themselves.
Summary
:link,:visitedand:any-linkstyle real links.:visitedcan only change colors, and scripts can't detect it.:targetmatches the element named by the URL fragment.:hover,:active,:focus,:focus-visibleand:focus-withinreact to the user. Don't rely on hover for essential content, and keep link rules in link, visited, focus, hover, active order.:focus-visibleshows focus when it helps, chiefly for keyboard users, and is where focus rings belong.- Form controls expose states such as
:checked,:disabled,:required,:in-rangeand:placeholder-shown. Prefer:user-invalidto:invalidfor error styles. :open,:popover-open,:modaland:fullscreenreflect open and top-layer states, and media elements have playback states.:lang()and:dir()match inherited language and direction, which attribute selectors can't.
Practice questions
A stylesheet has the rules below, in this order. Why don't visited links turn red on hover, and how do you fix it?
a:hover { color: red; }
a:visited { color: purple; }
Answer
A hovered visited link matches both rules, which have the same specificity, so the later one, :visited, wins. Move a:hover after a:visited (and keep :active last).
You want a signup field to show a red border only after the user has typed an invalid email and moved on. Which pseudo-class do you use, and why not :invalid?
Answer
input:user-invalid. :invalid applies as soon as the field is invalid, including before the user has typed anything when the field is required, so the form would show errors on load. :user-invalid waits for the user to interact with the field or submit the form.
Write a rule that highlights a whole <fieldset> while any control inside it has focus.
Answer
fieldset:focus-within { border-color: #f4c95d; background: #fffbea; }
A page sets <html lang="de">, and contains <p>Guten Tag</p>. Which matches the paragraph: p:lang(de) or p[lang|="de"]?
Answer
Only p:lang(de). The paragraph inherits its language from the <html> element, which :lang() takes into account. The attribute selector requires a lang attribute on the paragraph itself, and it has none.
Why is a hover effect that increases a link's font size a bad idea?
Answer
Changing the font size changes the link's size and can reflow the surrounding text, so the page jumps under the pointer. The link may move away from the pointer, ending the hover, which can make it flicker. Change properties that don't affect layout, such as color, underline or transform, instead.
Previous: Structural Pseudo-Classes: (), (), of S and Friends
Next: Logical Pseudo-Classes: (), (), () and the () Parent Selector

More in CSS Course
Quiz: CSS Delicate Details
Twenty-five questions on the edge cases that surprise experienced developers: invalid custom properties, shorthands that reset values, layer order with !important, containing blocks, margin collapsing, specificity of :is() and :where(), intrinsic minimum sizes, and more, each checked in Chrome.
Quiz: CSS Interview Questions
Thirty front-end interview questions: cascade, specificity and layers, box model and margin collapsing, stacking contexts, positioning, flexbox and grid, responsive design, custom properties, performance, accessibility, modern selectors and architecture.
Quiz: CSS Course Final Exam
Thirty questions across the whole CSS course: syntax and error handling, selectors, the cascade and layers, values and units, color, the box model, backgrounds, positioning, flexbox, grid, responsive design, typography, generated content, effects, transforms, motion and architecture.
Quiz: CSS Architecture, Tooling and Debugging (CSS Part 17)
Twenty questions on modular CSS and BEM, layering a stylesheet, design tokens and theming, pattern libraries and safe refactoring, preprocessors and build tools, the at-rules reference, and debugging common CSS problems.
Discussion
Sign in to ask a question or share what you learned.