Chapter 05 of 33

Pseudo-classes & Pseudo-elements

So far our selectors have matched elements by what they are (type, class, ID, attributes) and where they sit (combinators). But many styling needs depend on things that are not written in the HTML at all:

  • Is the mouse currently over this button?

  • Is this the first item of the list? Every second row of the table?

  • Is this checkbox checked? Is this input filled in incorrectly?

  • Can I style just the first letter of a paragraph, or add an icon before a link without changing the HTML?

CSS answers these with pseudo-classes and pseudo-elements. This chapter builds on CSS Selectors and Combinators & Attribute Selectors.


Pseudo-class vs Pseudo-element

A pseudo-class (one colon, :hover) selects an existing element when it is in a particular state or position.

A pseudo-element (two colons, ::before) selects a part of an element, or creates a virtual element, that doesn't exist as a separate tag in the HTML.

PointPseudo-classPseudo-element
Syntax:name::name
TargetsA whole existing element, conditionallyA part of an element, or generated content
Examples:hover, :first-child, :checked::before, ::first-letter, ::placeholder
How many in one selector?Any number: a:hover:focus-visibleNormally one, at the end: p::first-line

The double colon was introduced to tell the two apart. For backward compatibility, browsers still accept a single colon for the four oldest pseudo-elements (:before, :after, :first-line, :first-letter), but new code should use ::.


Part 1: Pseudo-classes

User-action pseudo-classes

Pseudo-classMatches when...
:hoverThe pointer is over the element
:activeThe element is being activated (mouse button held down on it)
:focusThe element has keyboard/input focus
:focus-visibleThe element has focus and the browser decides a focus ring should be shown (typically keyboard navigation)
:focus-withinThe element or any descendant has focus
.btn {
  background: #2563eb;
  color: white;
  padding: 10px 18px;
  border: none;
}

.btn:hover {
  background: #1d4ed8;           /* darker on hover */
}

.btn:active {
  transform: translateY(1px);    /* looks "pressed" */
}

.btn:focus-visible {
  outline: 3px solid #f59e0b;    /* clear ring for keyboard users */
  outline-offset: 2px;
}

form:focus-within {
  background: #f0f7ff;           /* highlight the form being filled */
}

Why :focus-visible? Many designers removed focus outlines (outline: none) because they disliked the ring appearing after a mouse click. That makes the site unusable for keyboard users. :focus-visible (Baseline since 2022) solves it: browsers show it for keyboard focus but usually not for mouse clicks on buttons. Never remove focus styles without providing a replacement.

Remember that :hover doesn't exist on touch screens in the same way — never hide essential information behind hover only.

Pseudo-classMatches
:linkAn <a> with href that has not been visited
:visitedA link the user has already visited
:any-linkAny link with href, visited or not

All four link-state rules below have the same specificity, so the later one wins when several match (a visited link that is hovered matches both :visited and :hover). That's why the traditional order is Link, Visited, Hover, Active — "LoVe HAte":

a:link    { color: #1d4ed8; }
a:visited { color: #7c3aed; }
a:hover   { color: #dc2626; }
a:active  { color: #ea580c; }

If you put :hover before :visited, visited links would never show the hover colour.

Privacy note: to stop websites from discovering your browsing history, browsers only let :visited change colour-related properties (such as color, background-color, border-color, outline-color), and JavaScript cannot read the visited styling.

Structural pseudo-classes (position in the parent)

Pseudo-classMatches an element that is...
:first-childthe first child of its parent
:last-childthe last child of its parent
:only-childthe only child of its parent
:nth-child(An+B)at a position given by the formula, counting from the start
:nth-last-child(An+B)same, counting from the end
:first-of-type, :last-of-type, :only-of-typefirst / last / only among siblings of the same element type
:nth-of-type(An+B)at a position counted only among siblings of the same type
:emptyan element with no children and no text
:rootthe root element of the document (<html>)

Understanding the An+B formula

In :nth-child(An+B), n takes the values 0, 1, 2, 3, ... and the element positions start at 1. The selector matches every position that the formula produces (positions ≤ 0 are ignored).

SelectorCalculation (n = 0, 1, 2, 3, ...)Positions matched
:nth-child(3)just 33
:nth-child(2n) = even0, 2, 4, 62, 4, 6, ...
:nth-child(2n+1) = odd1, 3, 5, 71, 3, 5, ...
:nth-child(3n)0, 3, 6, 93, 6, 9, ...
:nth-child(n+3)3, 4, 5, 63 and every one after it
:nth-child(-n+3)3, 2, 1, 0, −11, 2, 3 (the first three)
:nth-last-child(1)1 from the endthe last child (same as :last-child)

Worked example — zebra-striped list:

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
</ul>
li:first-child   { color: green; }
li:last-child    { color: red; }
li:nth-child(2n) { background: #eeeeff; }
li:nth-child(3)  { font-weight: bold; }

Output:

One    ← green
Two    ← light purple background      (position 2 is even)
Three  ← bold                          (position 3)
Four   ← light purple background      (position 4 is even)
Five   ← red                           (last child)

A common table pattern: tr:nth-child(even) { background: #f5f5f5; } for readable striped rows, and tr:nth-child(n+3) to style every row from the third onward.

:first-child vs :first-of-type — a classic trap

<div class="box">
  <h3>Title</h3>
  <p>First paragraph</p>
  <p>Second paragraph</p>
</div>
.box p:first-child   { color: blue; }
.box p:first-of-type { text-decoration: underline; }

Output: "First paragraph" is underlined but not blue.

Why? p:first-child means "a p that is the first child of its parent". The first child of .box is the h3, so no p qualifies. p:first-of-type means "the first p among its siblings", ignoring the h3, so it matches.

The same distinction applies to :nth-child() vs :nth-of-type(): -child counts all siblings, -of-type counts only siblings with the same tag name.

Filtering the count: :nth-child(An+B of S)

Selectors Level 4 lets you count only siblings that match a selector (Baseline since 2023):

/* the 2nd item that has class "done" */
li:nth-child(2 of .done) {
  background: #ccffcc;
}

With items a.done, b, c.done, d.done, this highlights c: it is the second .done item, even though it is the third child overall. Note that this is different from .done:nth-child(2), which would require the second child overall to have the class (here, b — which doesn't, so nothing matches).

:empty

.alert:empty {
  display: none;   /* hide alert boxes that have no message */
}

An element containing only an HTML comment counts as empty. But in current browsers an element containing even a single space or line break is not empty, so <div class="alert"> </div> does not match.

Form-state pseudo-classes

Pseudo-classMatches
:checkedChecked checkboxes/radio buttons, selected options
:disabled / :enabledForm controls that are / aren't disabled
:required / :optionalInputs with / without the required attribute
:valid / :invalidInputs whose value passes / fails HTML validation, checked immediately
:user-valid / :user-invalidSame, but only after the user has interacted with the field (Baseline since 2023)
:placeholder-shownAn input currently showing its placeholder text
<input type="checkbox" id="terms" checked>
<label for="terms">I agree</label>

<input type="email" required>
input:checked + label {
  font-weight: bold;
  color: green;
}

input:user-invalid {
  border: 2px solid red;
}

Output: the label next to the ticked checkbox turns bold and green (and returns to normal when unticked — no JavaScript needed). The email field turns red only after the user has typed an invalid address and moved on, or tried to submit the form. With plain :invalid, the empty required field would be red as soon as the page loads, which feels like scolding the user before they've done anything.

Other useful pseudo-classes

  • :target — the element whose id matches the URL fragment (e.g. the section you jumped to via #faq).

  • :root — the <html> element; commonly used to declare CSS variables (see CSS Variables (Custom Properties)).

  • :lang(hi) — elements in a given language, e.g. to choose a Devanagari font.


Logical Pseudo-classes: :not(), :is(), :where(), :has()

These take a selector list as an argument.

:not() — negation

/* every tag except the "hot" ones is faded */
.tags span:not(.hot) {
  opacity: 0.5;
}

/* every list item except the last gets a bottom border */
li:not(:last-child) {
  border-bottom: 1px solid #dddddd;
}

The second rule is a neat pattern: instead of adding a border to all items and then removing it from the last one, you style "all but the last" directly. Modern browsers accept a list inside :not(), e.g. :not(.a, .b).

:is() — shorter selector lists

/* Without :is() */
article h1, article h2, article h3 { line-height: 1.2; }

/* With :is() — same meaning */
article :is(h1, h2, h3) { line-height: 1.2; }

Unlike a plain selector list, :is() is forgiving: an invalid selector inside it is ignored instead of killing the whole rule (recall the selector-list trap from CSS Selectors).

:where() — same as :is(), but with zero specificity

:where() matches exactly like :is(), but contributes no specificity. That makes it ideal for default styles that should be easy to override:

:where(ul, ol) {
  padding-left: 1.5rem;   /* any later class can override this easily */
}

:is(), :not() and :has() take the specificity of their most specific argument; :where() always counts as zero. The exact numbers are worked out in Specificity, Inheritance & the Cascade.

:has() — the "parent selector"

A:has(B) selects A if, relative to A, the selector B matches something — usually a descendant:

/* cards that contain an image get a different layout */
.card:has(img) {
  padding: 0;
}

/* a label that is immediately followed by a required input */
label:has(+ input:required)::after {
  content: " *";
  color: red;
}

This finally lets CSS style an element based on its children or following siblings — something combinators alone cannot do. :has() has been Baseline since December 2023. Note that, unlike :is() and :where(), its argument list is not forgiving: one invalid selector inside :has() makes the whole rule invalid, so it is ignored. Advanced patterns are covered in Modern CSS: :has(), Nesting, clamp() & Logical Properties.


Part 2: Pseudo-elements

Pseudo-elementSelects / creates
::beforeA generated child placed before the element's content
::afterA generated child placed after the element's content
::first-letterThe first letter of the first line of a block
::first-lineThe first formatted line of a block (changes with width)
::placeholderThe placeholder text of an input/textarea
::selectionText the user has highlighted
::markerThe bullet or number of a list item
::file-selector-buttonThe button of <input type="file">

::before and ::after

These create an extra, virtual inline box inside the element — as its first child (::before) or last child (::after). They are only generated if the content property is set (it can be an empty string).

.quote::before {
  content: "“";
  color: crimson;
  font-size: 1.5em;
}

.quote::after {
  content: "”";
  color: crimson;
  font-size: 1.5em;
}

.new::after {
  content: "NEW";
  background: crimson;
  color: white;
  font-size: 10px;
  padding: 1px 4px;
  margin-left: 6px;
  border-radius: 3px;
}
<p class="quote">CSS is fun</p>
<a class="new" href="/courses">Courses</a>

Output:

“CSS is fun”      ← large crimson quote marks added by CSS
Courses [NEW]     ← small white-on-crimson badge after the link

The HTML contains neither the quote marks nor the word "NEW" — CSS generated them.

Key facts about ::before/::after:

  • Without content, nothing appears. For purely decorative shapes use content: "" plus a width, height and display: block or inline-block.

  • They are not part of the DOM: JavaScript can't select them, and the generated text usually can't be selected/copied by the user.

  • They don't work on replaced elements such as <img> and most form controls, because those elements have no content box of their own to insert children into.

  • Screen readers may or may not announce the generated text, so never put important information only in content.

::first-letter and ::first-line

<p class="intro">CSS lets you style the first letter and the first line of a paragraph without adding any extra tags to your HTML.</p>
.intro::first-letter {
  font-size: 2.5em;
  font-weight: bold;
  color: navy;
}

.intro::first-line {
  text-transform: uppercase;
}

Output: the paragraph starts with a large navy "C" (a drop-cap style), and the whole first line is in capitals. If you resize the window so more words fit on the first line, more words become uppercase — ::first-line follows the actual rendered line, not a fixed number of characters.

::placeholder, ::selection and ::marker

input::placeholder {
  color: teal;
  font-style: italic;
}

::selection {
  background: #fde68a;   /* highlighted text gets a yellow background */
  color: #111111;
}

li::marker {
  color: crimson;        /* red bullets, black text */
}

These three accept only a limited set of properties — mostly colours and font/text properties. For example, you can't give ::marker a margin or padding.


Combining Everything

Pseudo-classes and pseudo-elements combine with everything from the previous chapters. The pseudo-element must come last:

/* show an arrow after a nav link only while it is hovered */
nav a:hover::after {
  content: " →";
}

/* first paragraph of every article, first letter only */
article > p:first-of-type::first-letter {
  font-size: 2em;
}

/* inline list separated by commas: "HTML, CSS, JS" */
.inline-list li {
  display: inline;
}

.inline-list li:not(:last-child)::after {
  content: ", ";
}

The last pair turns <ul class="inline-list"><li>HTML</li><li>CSS</li><li>JS</li></ul> into the single line HTML, CSS, JS — a comma after every item except the last, without touching the HTML.


Common Mistakes

  • Space before the colon: a :hover means "any hovered element inside an a". Write a:hover.

  • Forgetting content on ::before/::after — nothing renders.

  • Using ::before on <img> or <input> and wondering why it doesn't appear.

  • Mixing up :first-child and :first-of-type when another element type comes first.

  • Wrong link order (hover before visited) so hover appears not to work on visited links.

  • outline: none on :focus without a :focus-visible replacement — breaks keyboard accessibility.

  • Expecting :empty to match whitespace-only elements — it doesn't in current browsers.

  • Pseudo-element in the wrong place: p::before:hover is not supported by browsers, so the whole rule is dropped. Put pseudo-classes first and the pseudo-element last: p:hover::before.


Interview / Exam Questions

1. What is the difference between a pseudo-class and a pseudo-element?

A pseudo-class (:hover, :nth-child()) selects existing elements based on state or position. A pseudo-element (::before, ::first-line) selects a part of an element or generates virtual content that isn't in the HTML. Pseudo-classes use one colon, pseudo-elements two.

2. Which list items does li:nth-child(3n+1) select?

Positions 1, 4, 7, 10, ... (n = 0 gives 1, n = 1 gives 4, n = 2 gives 7, and so on).

3. How do you select the first 4 items of a list? The last 2?

First four: li:nth-child(-n+4) (gives positions 4, 3, 2, 1). Last two: li:nth-last-child(-n+2).

4. A div contains h2, p, p. Does div p:first-child match anything? What about div p:nth-of-type(1)?

div p:first-child matches nothing, because the first child is the h2. div p:nth-of-type(1) matches the first paragraph, since it counts only p siblings.

5. Why must links be styled in LVHA order?

:link, :visited, :hover and :active have equal specificity, and an element can match several at once (e.g. a visited link being hovered). With equal specificity the later rule wins, so :hover must come after :link/:visited, and :active last, for each state to show.

6. Why does ::before not work on an img element?

<img> is a replaced element: its content is an external image, not a box of child content. ::before/::after insert children inside an element's content, so they are not rendered for replaced elements.

7. What is the difference between :is() and :where()?

Both match any element that matches one of the selectors in their list, and both are forgiving of invalid selectors. :is() takes the specificity of its most specific argument; :where() always has zero specificity.


Summary

  • Pseudo-classes (:) select elements by state or position: :hover, :focus-visible, :checked, :nth-child(), :not(), :has().

  • Pseudo-elements (::) style parts or generate content: ::before, ::after, ::first-letter, ::marker, ::placeholder.

  • An+B: n counts from 0, positions from 1. 2n = even, 2n+1 = odd, -n+3 = first three.

  • -child counts all siblings; -of-type counts siblings of the same tag.

  • Link order: :link, :visited, :hover, :active. Use :focus-visible for accessible focus rings.

  • ::before/::after need content and don't work on replaced elements.

  • :is()/:where() are forgiving; :where() has zero specificity.

We've now met many selectors with different "strengths". In the next chapter, Specificity, Inheritance & the Cascade, we'll learn exactly how the browser decides which rule wins when several of them target the same element.