Tutorials CSS Pseudo-classes
Ch 34 / 60
Chapter 34 Intermediate 10 min read CSS

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.

What you'll learn
User-action pseudo-classes: :hover, :focus, :active
Form state: :checked, :disabled, :valid, :required
Structural: :nth-child, :first-child, :last-child
Negation: :not() — exclude elements
Logical: :is(), :where() — grouping
Relational: :has() — the parent selector

What 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 { ... }

:hover
Matches when the user's pointer is over the element. No class change needed — the browser tracks the state.
:nth-child(2)
Matches the second child of its parent. The position is structural — determined by the DOM, not by a class.
:checked
Matches a checkbox or radio input that is currently checked. State-driven without JavaScript.
CSS — Pseudo-class syntax
/* 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

User Action

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:

:hover
Pointer is over the element. Works on any element, not just links.
:focus
Element has keyboard focus (Tab key or click on input). Critical for accessibility.
:focus-visible
Focus ring visible only for keyboard navigation — not mouse click. Best practice over :focus alone.
:focus-within
Matches if the element OR any of its descendants has focus. Style a form group when any input is focused.
:active
Element is being activated (mouse button held down, key pressed).
:visited
Link has been visited. Limited styling for privacy (only color properties).
:link
Unvisited anchor (<a>) with an href that hasn't been visited yet.
:target
Element whose id matches the URL fragment (#section). Used for anchor navigation effects.
Live demo — hover, focus, and active below (interact with them)
CSS — User-action pseudo-classes
/* ── :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

Form State

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 — checkbox/radio is on
:disabled — input is not interactive
:valid / :invalid — browser validation
:required / :optional
:required
:optional
CSS — Form state pseudo-classes
/* ── :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

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

1
2
3
4
5
6
7
8

:nth-child(3n+1) — every 3rd starting at 1

1
2
3
4
5
6
7
8

:first-child + :last-child

1st
2
3
4
5
Last

:nth-last-child(2) — second from end

1
2
3
4
5th
6
:first-child
First child of its parent.
:last-child
Last child of its parent.
:nth-child(n)
nth child. Accepts: numbers, 2n (even), 2n+1 (odd), even, odd.
:nth-last-child(n)
Counts from the end instead of the start.
:only-child
Element that is the only child of its parent.
:first-of-type
First element of its type among siblings.
:last-of-type
Last element of its type among siblings.
:nth-of-type(n)
nth element of its type. More predictable than nth-child when mixing element types.
:only-of-type
The only element of its type among siblings.
:empty
Matches elements with no children (including text nodes).
:root
The root element of the document — the <html> element. Used for CSS custom property declarations.
:scope
The element that is the reference for relative selectors. In stylesheets, same as :root.
CSS — Structural pseudo-classes
/* ── 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:

Item A
Item B
Item C (excluded)
Item D
Item E
Item F (excluded)

li:not(.excluded) — matches A, B, D, E but skips C and F

CSS — :not()
/* 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

Logical

Both :is() and :where() group selectors together for concise matching. The only difference is specificity:

:is() — takes highest specificity of arguments
/* 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.

:where() — zero specificity always
/* 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.

CSS — :is() and :where()
/* ── :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

Relational

: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:has(img)

article with img → different layout applied

form:has(input:invalid)
⚠ form has invalid input → show error banner
CSS — :has()
/* ── 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
Free Resource
CSS3 Cheat Sheet — All Properties & Selectors
Complete reference covering all CSS pseudo-classes and pseudo-elements with examples.
Download PDF

Try It Yourself

Experiment with pseudo-classes. Hover, click, tab through inputs, and try changing the nth-child formulas:

Live Editor
✎ Editor
👁 Preview
Featured Course — Enroll Now
Modern Web Development With AI
Master HTML, CSS, JavaScript, React and Node.js with real projects and placement support.
120+
Chapters
40 hrs
Content
10 Real
Projects
4.9 ⭐
Rating
HTML5CSS3JavaScriptReact.jsNode.jsTailwind CSSAI Tools

Quick Check — Chapter 34

Questions & Answers
Both pseudo-classes match elements that have focus, but they differ in when the browser considers focus visually necessary:

: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.
Both count children within a parent, but they count differently:

: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.
Both :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 image

2. Form validation parent styling: form:has(input:invalid) — style the form when any input is invalid

3. Sibling targeting: h2:has(+ p) — h2 that is directly followed by a paragraph

4. 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 images

6. Navigation state: nav:has(a.active) — highlight nav when any link is active

Browser 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 validation

Together: 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.
Multiple Choice Questions
Question 1 of 5
The correct order for link pseudo-classes (to prevent one from overriding another) is:
Question 2 of 5
Which selector matches the 1st, 4th, 7th, 10th child (every 3rd starting from 1)?
Question 3 of 5
What specificity does :where(h1, h2, #title) have?
Question 4 of 5
Which selector highlights a form's container when any of its inputs has an error?
Question 5 of 5
Which pseudo-class matches an element only when the user navigated to it by keyboard, but NOT when they clicked it with a mouse?
Chapter Summary
  • 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-child vs :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):invalid shows error only after user has typed, not immediately on page load.
~10 min read
Intermediate level
Chapter 34 of 60

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel