CSS Pseudo-classes
A pseudo-class is a keyword added to a selector with a colon (:) that targets elements in a specific state or structural
position that can't be expressed with a simple element, class, or ID selector. They're the key to
interactive, state-aware styling with pure CSS — no JavaScript needed for hover effects, form validation,
zebra tables, or even parent-element targeting.
:hover, :focus, :active:checked, :disabled, :valid, :required:nth-child, :first-child, :last-child:not() — exclude
elements:is(), :where() — grouping:has() — the parent
selectorWhat Is a Pseudo-class?
A pseudo-class targets an element based on information outside the HTML — a
user action, document position, or element state. Syntax: selector:pseudo-class { ... }
/* Selector followed by colon and pseudo-class name */
a:hover { color: blue; }
button:focus { outline: 2px solid blue; }
input:required { border-color: red; }
li:first-child { font-weight: bold; }
li:not(.active) { opacity: .5; }
/* Chaining pseudo-classes */
a:visited:hover { color: purple; }
input:focus:valid { border-color: green; }
/* Combining with other selectors */
.btn:hover { } /* class + pseudo */
#nav li:last-child { } /* id + element + pseudo */
article p:first-child { } /* descendant + pseudo */
User-Action Pseudo-classes
These pseudo-classes respond to the user's interactions with the page — mouse, keyboard, and touch. They are the foundation of interactive CSS without JavaScript:
<a>) with an href that
hasn't been visited yet./* ── :hover ── */
.btn:hover {
background: #264de4;
transform: translateY(-2px);
}
/* ── :focus — for inputs and interactive elements ── */
input:focus {
outline: none;
border-color:#4a8af4;
box-shadow: 0 0 0 3px rgba(38,77,228,.2);
}
/* ── :focus-visible — only for keyboard navigation ── */
.btn:focus { outline: none; } /* remove default */
.btn:focus-visible { outline: 3px solid #4a8af4; } /* add back for keyboard only */
/* ── :focus-within — parent tracks any focused child ── */
.form-group:focus-within {
border-color: #4a8af4;
background: rgba(38,77,228,.04);
}
/* ── :active ── */
.btn:active { transform: scale(0.97); }
/* ── Link states — order matters: LVHA ── */
a:link { color: #4a8af4; }
a:visited { color: #a855f7; }
a:hover { color: #f97316; }
a:active { color: #ef4444; }
/* Memory: LoVe HAte */
/* ── :target — style element matching URL hash ── */
:target {
scroll-margin-top: 80px;
background: rgba(38,77,228,.08);
border-left: 4px solid #4a8af4;
}
Form State Pseudo-classes
These pseudo-classes reflect the state of form elements — whether they're checked, disabled, valid, or required. They enable CSS-only form validation feedback without any JavaScript:
/* ── :checked ── */
input:checked { accent-color: #264de4; }
/* Style a label when its checkbox is checked */
input:checked + label { color: #264de4; font-weight: bold; }
/* ── :disabled / :enabled ── */
input:disabled { opacity: .5; cursor: not-allowed; }
button:disabled{ background: #94a3b8; cursor: not-allowed; }
/* ── :valid / :invalid ── */
input:valid { border-color: #22c55e; }
input:invalid { border-color: #ef4444; }
/* ⚠ :invalid fires immediately (before user types)
Combine with :not(:placeholder-shown) or JS class */
input:not(:placeholder-shown):invalid {
border-color: #ef4444;
}
/* ── :required / :optional ── */
input:required { border-left: 3px solid #f97316; }
input:optional { border-left: 3px solid #94a3b8; }
/* ── :read-only / :read-write ── */
input:read-only { background: rgba(0,0,0,.05); }
/* ── :placeholder-shown ── */
input:placeholder-shown { font-style: italic; }
/* ── :indeterminate — checkbox in mixed state ── */
input:indeterminate { accent-color: #f97316; }
Structural Pseudo-classes
Structural pseudo-classes select elements based on their position in the document tree. They're the key to zebra-stripe tables, first/last-child styling, and counting-based selection — all without any extra classes:
:nth-child() — visual examples
:nth-child(2n) — every even item
:nth-child(3n+1) — every 3rd starting at 1
:first-child + :last-child
:nth-last-child(2) — second from end
2n (even), 2n+1 (odd), even, odd.<html> element. Used for CSS custom property declarations./* ── Basic position ── */
li:first-child { font-weight: bold; }
li:last-child { border-bottom: none; } /* remove last border */
li:only-child { list-style: none; } /* single item — no bullet */
/* ── :nth-child() ── */
tr:nth-child(even) { background: rgba(0,0,0,.04); } /* zebra table */
tr:nth-child(odd) { background: white; }
li:nth-child(3n) { color: red; } /* every 3rd */
li:nth-child(n+4) { display: none; } /* hide items 4 onwards */
li:nth-child(-n+3) { font-weight: bold; } /* first 3 items */
/* ── :nth-child vs :nth-of-type ── */
/* HTML: <p><h2>...<p>...<p>... */
p:nth-child(2) { } /* p that is 2nd child — may not match if h2 is 1st */
p:nth-of-type(2) { } /* 2nd p element — always reliable */
/* ── :empty ── */
td:empty { background: rgba(239,68,68,.08); } /* highlight empty cells */
div:empty { display: none; } /* hide empty divs */
/* ── :root — for CSS variables ── */
:root {
--color-primary: #264de4;
--spacing-base: 16px;
}
:not() — The Negation Pseudo-class
:not() selects elements that do
not match the given selector. It accepts any valid selector including classes, types,
attributes, and even other pseudo-classes:
li:not(.excluded) — matches A, B, D, E but skips C and F
/* Basic :not() */
li:not(.active) { opacity: .5; }
input:not([disabled]) { cursor: text; }
p:not(:first-child) { margin-top: 1em; }
a:not([href]) { cursor: default; }
/* :not() with multiple selectors (modern CSS) */
:not(h1, h2, h3, h4) { font-size: 1rem; }
p:not(.lead, .intro) { color: #6b7280; }
/* Chaining multiple :not() */
li:not(:first-child):not(:last-child) {
border-bottom: 1px solid var(--border);
}
/* Common pattern: remove last child border */
li { border-bottom: 1px solid #e5e7eb; }
li:last-child{ border-bottom: none; }
/* Or more concise: */
li:not(:last-child) { border-bottom: 1px solid #e5e7eb; }
:is() and :where() — Logical Grouping
Both :is() and :where() group selectors together for concise matching. The only difference
is specificity:
/* Verbose */ header h1, header h2, main h1, main h2 { } /* :is() — concise */ :is(header, main) :is(h1, h2) { }
Specificity = highest among
arguments. :is(#id, .class) has ID-level specificity.
/* Base styles — easy to override */ :where(article, section, aside) :where(h1, h2, h3) { font-weight: 600; }
Specificity = always 0. Any later rule can override — great for base/reset styles.
/* ── :is() — concise selector grouping ── */
/* Instead of repeating: */
nav a:hover, footer a:hover, aside a:hover { color: blue; }
/* Use :is() */
:is(nav, footer, aside) a:hover { color: blue; }
/* Nested heading selectors */
:is(h1, h2, h3, h4, h5, h6) { line-height: 1.2; }
/* ── :where() — same grouping, but zero specificity ── */
/* Perfect for base/reset styles that are easy to override */
:where(ul, ol) { padding-left: 1.5rem; }
:where(p, li) { line-height: 1.6; }
/* Any single-class rule will override :where() */
.compact ul { padding-left: 0; } /* overrides :where(ul) ✓ */
/* Specificity comparison:
:is(#id, .class, p) → specificity of #id = (1,0,0)
:where(#id, .class) → always (0,0,0)
p.class → (0,1,1)
#id → (1,0,0) */
:has() — The Parent Selector
:has() selects an element if it contains a
descendant matching the argument. It's the long-awaited "parent selector" in CSS. It enables
styling parents, siblings, or containers based on their contents:
article with img → different layout applied
/* ── The parent selector ── */
/* Style an article that contains an image */
article:has(img) {
display: grid;
grid-template-columns: 120px 1fr;
}
/* Style form when it contains an invalid input */
form:has(input:invalid) {
border: 2px solid #ef4444;
}
/* Sibling selection using :has() */
h2:has(+ p) { margin-bottom: 0.5rem; }
/* h2 that is immediately followed by a p */
/* Card layout change based on image presence */
.card:not(:has(img)) { padding-top: 2rem; } /* no image → add top padding */
.card:has(img) { padding-top: 0; } /* image present → no padding */
/* Navigation — active link ancestor */
nav:has(a.active) { background: rgba(38,77,228,.05); }
/* Select parent when child is focused */
.form-group:has(input:focus) { box-shadow: 0 0 0 3px rgba(38,77,228,.15); }
/* :has() specificity = same as :is() */
/* Browser support: Chrome 105+, Safari 15.4+, Firefox 121+ */
Complete Pseudo-class Reference
| Pseudo-class | Category | Matches when |
|---|---|---|
| :hover | Action | Pointer is over the element |
| :focus | Action | Element has keyboard/click focus |
| :focus-visible | Action | Focus ring shown (keyboard only) |
| :focus-within | Action | Element or a descendant has focus |
| :active | Action | Being activated (mouse/key pressed) |
| :link / :visited | Link | Unvisited / visited anchor links |
| :target | Link | id matches URL fragment |
| :checked | Form | Checkbox/radio is selected |
| :disabled / :enabled | Form | Form element is enabled/disabled |
| :valid / :invalid | Form | Input passes/fails browser validation |
| :required / :optional | Form | Has/lacks required attribute |
| :placeholder-shown | Form | Placeholder is currently visible |
| :first-child / :last-child | Structural | First / last child in parent |
| :nth-child(n) | Structural | nth child — accepts an+b formula |
| :nth-of-type(n) | Structural | nth child of specific element type |
| :only-child | Structural | Is the only child in its parent |
| :empty | Structural | Has no children (including text) |
| :root | Structural | Root element (<html>) |
| :not(s) | Logical | Does NOT match selector s |
| :is(s1, s2) | Logical | Matches any of the listed selectors |
| :where(s1, s2) | Logical | Same as :is() but always zero specificity |
| :has(s) | Relational | Contains a descendant matching s |
Try It Yourself
Experiment with pseudo-classes. Hover, click, tab through inputs, and try changing the nth-child formulas:
Quick Check — Chapter 34
:focus — matches any focused element regardless of
how focus was applied (mouse click, touch, keyboard Tab). Using button:focus { outline: none } removes the focus ring completely — which
harms keyboard users who rely on it for navigation.:focus-visible — matches only when the browser
determines a visible focus indicator is necessary. In practice: it matches when the user navigated with
the keyboard (Tab, arrow keys), but NOT when they clicked with a mouse. This means mouse users don't see
the focus ring (which they don't need), but keyboard users do (which they require for
accessibility).Best practice:
button:focus { outline: none } + button:focus-visible { outline: 3px solid #264de4 } — removes
distracting outline on click while preserving it for keyboard navigation.
:nth-child(n) — counts all children in the
parent regardless of type, then checks if the element at that position matches the selector. If the HTML
is <h2><p><p>, then p:nth-child(2) matches the first <p> (which is the 2nd child overall). But p:nth-child(1) would NOT match anything because child #1 is an <h2>.:nth-of-type(n) — counts only children of the
same element type. p:nth-of-type(1) always matches the
first <p> regardless of what other elements are in the
parent.Rule of thumb: use
:nth-of-type when you have mixed element types in
a parent. Use :nth-child when all children are the same type or when
you need to count based on position, not type.
:is() and :where() group
multiple selectors and match any of them. They look identical in output — the only difference is
specificity::is() — takes the specificity of its most
specific argument. :is(#id, .class, p) has ID-level
specificity (1,0,0) because #id is included. This can cause
unexpected override battles.:where() — always has zero
specificity (0,0,0), regardless of what's inside. This means any other rule targeting the
same element will override it, making it perfect for base/reset styles that should never win a
specificity battle.Use
:is() for standard selector grouping. Use :where() for default/reset styles that you want easily overridable — for
example in design system base layers.
:has() is the long-awaited parent selector in CSS.
Before it, you could only select descendants — never ancestors. :has() lets you select an element based on what it
contains.Key use cases:
1. Parent based on child presence:
article:has(img)
— article layout changes if it has an image2. Form validation parent styling:
form:has(input:invalid) — style the form when any input is
invalid3. Sibling targeting:
h2:has(+ p) — h2 that is
directly followed by a paragraph4. Focus-within alternative:
.form-group:has(input:focus) — highlight the group when any input inside
is focused (similar to :focus-within)5. Conditional layouts:
.card:not(:has(img)) —
different padding for cards without images6. Navigation state:
nav:has(a.active) — highlight
nav when any link is activeBrowser support: Chrome 105+, Safari 15.4+, Firefox 121+ (now widely supported).
input:invalid fires as soon as the page loads — before the user has
typed anything. An empty required email field is technically invalid immediately, so using input:invalid would show a red error border on every form field the
moment the page renders, before the user has even touched it. This is terrible UX.input:not(:placeholder-shown):invalid combines two
pseudo-classes:—
:not(:placeholder-shown) — matches when the placeholder is NOT
visible (i.e., the user has typed something, or the field has a value)—
:invalid — the value fails validationTogether: only show the error styling after the user has typed something and it's invalid. Empty fields don't get the error treatment. This is a common CSS-only form validation pattern that mimics "touched" state without JavaScript.
:where(h1, h2, #title)
have?- Pseudo-class — keyword after
:that targets elements by state, position, or relationship. No HTML changes needed. - User-action:
:hover(pointer over),:focus(has focus),:focus-visible(keyboard focus only),:focus-within(child has focus),:active(being pressed),:target(URL fragment). - Link states LVHA order:
:link→:visited→:hover→:active(LoVe HAte). - Form state:
:checked,:disabled,:valid/:invalid,:required/:optional,:placeholder-shown. - Structural:
:first-child,:last-child,:nth-child(an+b),:nth-of-type,:only-child,:empty,:root. :nth-childvs:nth-of-type: nth-child counts all siblings. nth-of-type counts only siblings of the same element type — more predictable with mixed elements.:not(s)— selects elements that do NOT match s. Can take multiple selectors. Chainable.:is(s1, s2)— groups selectors, specificity = most specific argument.:where()— same but always zero specificity (great for base styles).:has(s)— the parent selector. Selects an element if it contains a descendant matching s. Use for layout changes, form validation, sibling targeting.- Form validation tip:
input:not(:placeholder-shown):invalidshows error only after user has typed, not immediately on page load.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.