Thuta Learning
CSS
AdvancedWeb DevelopmentBeginner

Pseudo-classes

CSSLesson 2225 min

What you'll walk away with

  • Tell apart four groups of pseudo-classes: user action, form state, structure and relationship
  • Explain that :nth-child() counts every sibling, not a class, and fix it with :nth-child(n of .class)
  • Know the difference between :focus and :focus-visible and never remove the keyboard focus ring
  • Style a parent from its child's state with :has()

Explain it simply

Explain it simply

A class is a label you write into the HTML yourself. A pseudo-class is a temporary label the browser attaches for you: :hover while the mouse is over an element, :focus-visible while the keyboard has reached it, :checked while a checkbox is ticked. The label comes off again the moment the situation changes, and all you do is name it in a selector after a colon.

That is how you give interactive feedback without a line of JavaScript: change a button on hover, highlight the input being filled in, or stripe alternate table rows.

Problem → Why → Solution

The problem: asking for the second item and getting the first

A list starts with one li class="intro", followed by three li class="item". To color the second item (B) red, you write .item:nth-child(2). In the browser, A turns red instead of B, and every time an item is added or removed above it, the highlight jumps somewhere else.

list.html
<style>
  .item:nth-child(2) { color: red; } /* meant: the second .item */
</style>
<ul>
  <li class="intro">Today's tasks</li>
  <li class="item">A</li>   <!-- turns red: it is the 2nd child -->
  <li class="item">B</li>
  <li class="item">C</li>
</ul>

Why was A selected?

:nth-child(2) means "the second child of its parent", counting every sibling whatever its class, and only then is the .item filter checked. A is the second child and has .item, so it matches. To say "the second of the .item elements", write :nth-child(2 of .item), which counts only .item siblings.

Core concept: selecting conditions that are not in the HTML

A pseudo-class is a keyword attached to a selector with a single colon, as in a:hover or input:checked. Instead of looking at the element's attributes, it matches on a condition at that moment or on the element's position in the document. For specificity it counts the same as a class: .a:first-child (two class-level parts) beats p.a (one class plus one element).

GroupExamplesMatches when
User action:hover, :active, :focus, :focus-visibleThe user is pointing at, pressing or focusing it
Form state:checked, :disabled, :invalid, :user-invalidA form control is in that state
Structure:first-child, :last-child, :nth-child(), :nth-of-type()Its position among its siblings
Logic / relationship:not(), :is(), :has()It relates to another selector

:focus matches however the element received focus. :focus-visible matches only when the browser decides a focus ring should show: it matches after a Tab key press but not after a mouse click on a button, while text inputs match even on click because the user is about to type. That makes :focus-visible the better home for custom focus rings.

Pseudo-classes chain: button:hover:not(:disabled) means "a button being hovered that is not disabled". :has() looks the other way: .field:has(input:invalid) selects the parent .field whose input is invalid, parent styling that used to need JavaScript to toggle a class. All current major browsers support :has().

:is() and :where() group a list of selectors, so :is(h1, h2, h3):hover fits on one line. The specificity of :is() is that of its most specific argument, while :where() always counts as zero, which is why :where() suits default styles that should be easy to override later. One more detail: user-action states such as :hover and :active have equal specificity, so source order decides, and :active must come after :hover for the pressed style to win while the pointer is still over the element.

Mental model: labels the browser sticks on
  1. User or DOM changes a condition
  2. Browser adds or removes a label
  3. Selectors using that label re-match
  4. Condition gone: the style drops off

A pseudo-class style is never permanent; it lives only as long as the condition does.

General pattern

css
selector:state { property: value; }            /* :hover, :checked */
selector:nth-child(An+B) { property: value; }    /* position among siblings */
selector:nth-child(An+B of .class) { ... }       /* count only .class siblings */
selector:state:not(:other-state) { ... }         /* chain and exclude */
parent:has(child:state) { property: value; }     /* style the parent */

The pseudo-class is attached to the selector with no space. The An+B formula accepts forms like even (2n), odd (2n+1) or 3n, with n counting up from 0.

Example: hover, focus and zebra rows

These three rules show two pseudo-class groups: user action (:hover, :focus) and structure (:nth-child). Try the button and input with both the mouse and the Tab key, and read the breakdown for why the second rule is worth upgrading to :focus-visible.

.button:hover {
  transform: translateY(-2px);
}

.input:focus {
  outline: 2px solid dodgerblue;
}

tr:nth-child(even) {
  background-color: #f6f8fa;
}

Code breakdown

  1. .button:hover.button:hover {

    Matches only while a pointer is over the button. Touch screens have no real hover, so this lift must stay a bonus; never hide essential information behind hover.

  2. translateY(-2px)transform: translateY(-2px);

    Moves the button up 2px. transform does not affect layout, so neighbors stay put. With no transition it jumps instantly; the transitions lesson smooths it.

  3. .input:focusoutline: 2px solid dodgerblue;

    Gives the focused input a clear outline. :focus is fine for text inputs, but on buttons .button:focus-visible keeps the ring for keyboard users without showing it after every mouse click.

  4. tr:nth-child(even)tr:nth-child(even) {

    Selects the 2nd, 4th, 6th... rows of their parent. If the header row lives in <thead>, the <tbody> rows start counting from 1 on their own.

You should see
Hovering lifts the button 2px and it drops back when the pointer leaves. The focused input shows a 2px blue outline, and the 2nd, 4th... table rows get a light grey background.

Form states with :has()

:invalid matches from the moment the page loads: an empty required field is invalid before the user has typed anything, so red errors appear immediately. :user-invalid waits until the user has changed the field and moved on, and current major browsers support it. Combined with :has(), it can style the whole field wrapper, label and hint included. The browser still runs its own validation on submit, so this is about when the visual hint appears, not about whether the data is checked.

.field:has(input:user-invalid) {
  border-left: 4px solid crimson;
}

.field:has(input:user-invalid) .hint {
  color: crimson;
}

.field:has(input:focus-visible) label {
  font-weight: 600;
}

In real projects

Where this shows up in real projects

Every design system defines roughly five button states: default, hover, active, focus-visible and disabled. Even when the design file leaves some out, the developer has to add them so the interface stays clear to keyboard users, screen magnifier users and touch users. One of the most frequent accessibility audit findings is a focus ring removed by outline: none.

Data tables use :nth-child(even) for zebra stripes and tr:hover to highlight the row being read. Settings pages use :has() to change a whole card's border when its toggle checkbox is :checked, or to highlight the selected pricing plan, all without JavaScript. Menus that open on hover also get a :focus-within rule, so users arriving with Tab can see them too.

Common mistakes

Common mistakes

1. Removing the focus ring with no replacement

Writing button:focus { outline: none; } because the ring appears on every click leaves keyboard users with no idea where they are on the page. Instead of deleting the ring, style it on :focus-visible with an outline that fits your brand: it stays hidden for mouse clicks and appears for Tab.

2. Content that only appears on hover

With only .card:hover .actions { display: flex; }, phone users have no reliable way to reach the action buttons and keyboard users never see them. Add .card:focus-within to the selector, and wrap hover-only styling in @media (hover: hover) so touch devices show the actions all the time.

3. Errors on page load

input:invalid { border-color: red; } paints every required field red before the user has done anything, so a fresh form looks full of errors. Use :user-invalid to wait until the user has interacted with the field.

Best practices

Best practices

  • Write hover, focus-visible, active and disabled states together for every interactive element.
  • Remember :nth-child() counts all siblings; use :nth-child(n of .class) to count by class.
  • Always test with both the mouse and the Tab key.

Mini challenge

Mini challenge: a to-do list with real states

Style a to-do list with checkboxes using only pseudo-classes, no JavaScript.

  • Give alternate rows (1st, 3rd...) a light grey background
  • The last row has no bottom border
  • A li whose checkbox is ticked turns grey with line-through (use :has())
  • A checkbox shows a 3px blue outline only when reached with Tab
  • The disabled button is dimmed and gets no hover style
todo.html
<style>
  /* TODO: .todo - no bullets, no padding, 280px wide */
  /* TODO: padding and a bottom border on every row */
  /* TODO: stripe the 1st, 3rd, 5th... rows */
  /* TODO: no border on the last row */
  /* TODO: grey + line-through for a row whose checkbox is checked */
  /* TODO: keyboard-only focus ring on the checkboxes */
  /* TODO: hover colors for enabled buttons only, dim disabled ones */
</style>
<ul class="todo">
  <li><label><input type="checkbox" checked> Buy rice</label></li>
  <li><label><input type="checkbox"> Call Aye</label></li>
  <li><label><input type="checkbox"> Pay rent</label></li>
</ul>
<button disabled>Clear done</button>

Expected: "Buy rice" starts grey and struck through, and the "Buy rice" and "Pay rent" rows have the light grey stripe. "Pay rent" has no border. Clicking "Call Aye" strikes it through at once with no ring, but pressing Tab shows a 3px blue outline. The button is dimmed to opacity 0.5.

Show hint

li:has(input:checked) selects the row whose box is ticked. Use :focus-visible for the keyboard-only ring and button:hover:not(:disabled) to leave disabled buttons out.

Show solution
todo.html
<style>
  .todo { list-style: none; padding: 0; width: 280px; }
  .todo li { padding: 8px; border-bottom: 1px solid #ccc; }
  .todo li:nth-child(odd) { background: #f4f6f8; }
  .todo li:last-child { border-bottom: none; }
  .todo li:has(input:checked) { color: #888; text-decoration: line-through; }
  .todo input:focus-visible { outline: 3px solid #1a73e8; outline-offset: 2px; }
  button:hover:not(:disabled) { background: #1a73e8; color: white; }
  button:disabled { opacity: 0.5; cursor: not-allowed; }
</style>
<ul class="todo">
  <li><label><input type="checkbox" checked> Buy rice</label></li>
  <li><label><input type="checkbox"> Call Aye</label></li>
  <li><label><input type="checkbox"> Pay rent</label></li>
</ul>
<button disabled>Clear done</button>

Quick quiz 1 / 3

In <div><h2>Title</h2><p>One</p><p>Two</p></div>, which element does p:nth-child(2) select?

Quick quiz 2 / 3

You want no focus ring after a mouse click on a button, but keyboard users must still see one. What do you write?

Quick quiz 3 / 3

When a checkbox is ticked, the whole .card containing it should get a new border. Which selector is right?

What to remember

  • Pseudo-classes select conditions that are not in the HTML (state, position, relationship) and weigh the same as a class.
  • :nth-child() counts every sibling; use :nth-child(n of .class) to count by class.
  • Never delete the focus ring; restyle it with :focus-visible, and avoid hover-only content.
  • :has() styles a parent from its child's state, and :user-invalid waits for user interaction before showing errors.

CSS reference — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Pseudo-classes | Thuta Learning