Sub topic 1
Selectors you already use, and where pseudo selectors fit
A selector is the part of a CSS rule that decides which elements the rule applies to. Type, class, ID, and attribute selectors cover most everyday styling. They have gaps, though. This chapter reviews the selectors you know, shows what they can't express, and explains where pseudo-classes and pseudo-elements fill those gaps. Later chapters cover each pseudo selector in detail.
Prerequisites
This chapter assumes you can already do the following:
- Read and write basic HTML elements and attributes, such as
<a href="...">and<input type="checkbox">. - Write a CSS rule with a selector, a declaration block, properties, and values.
- Use type, class, ID, and attribute selectors.
- Use the descendant combinator (a space) and the child combinator (
>).
If any of these feel shaky, the refresher below should help. You also need a browser and a text editor to try the examples.
The selectors you already use
Each plain selector matches elements by something that is written in the HTML: the tag name, an attribute, or the element's place in the tree.
| Selector | Example | Matches |
|---|---|---|
| Type | `p` | Every `<p>` element |
| Class | `.note` | Elements with `class="note"` |
| ID | `#main` | The element with `id="main"` |
| Attribute | `a[target="_blank"]` | Links whose `target` attribute equals `_blank` |
| Descendant | `nav a` | Any `<a>` anywhere inside a `<nav>` |
| Child | `ul > li` | `<li>` elements that are direct children of a `<ul>` |
You can combine these into a compound selector by writing them without spaces. The compound selector a.external[rel="noopener"] matches only an <a> element that has the class external and the attribute rel="noopener". Every part must match at once.
nav a.current {
font-weight: bold;
}
form > input[type="email"] {
width: 100%;
}The first rule styles links with the class current inside a nav. The second styles email inputs that sit directly inside a form.
What plain selectors cannot do
The selectors above all read the markup as it was written. Three common needs fall outside that.
- State. A link has been visited, a button is under the mouse pointer, a checkbox is ticked, or a field has failed validation. None of this appears in the HTML source. It changes while the user interacts with the page.
- Position and relationship. You may want every other table row, the last item in a list, or a card that contains an image. You could add classes such as
class="odd"orclass="has-image"by hand. That breaks as soon as the content changes. - Parts of an element. You may want only the first letter of a paragraph, the bullet of a list item, or the text a user has highlighted. These parts have no tag of their own, so no type, class, or ID can reach them.
Pseudo selectors address these needs. The first two needs are met by pseudo-classes. The third is met by pseudo-elements.
Where pseudo selectors fit
A pseudo-class is a keyword added to a selector, after a single colon. It narrows the match to elements in a particular state or position. A pseudo-element is a keyword added after two colons. It targets a part of an element, or content the browser generates, instead of the element itself.
a:hover {
color: #c00;
}
p::first-letter {
font-size: 2em;
}In the first rule, a:hover still selects <a> elements. The :hover part only filters them to the ones under the pointer. In the second rule, p::first-letter does not select <p> elements. It selects the first letter inside each one.
The two-colon rule is the main syntax difference between the two kinds. The next chapter covers it in detail, including an older single-colon spelling that some pseudo-elements still accept for historical reasons.
Anatomy of a selector with pseudo parts
A compound selector has a fixed order. The type selector comes first, if there is one. Class, ID, attribute, and pseudo-class parts follow in any order. A pseudo-element goes last and appears at most once.
a.external:hover::after {
content: " \2197";
}Read it left to right:
aselects anchor elements..externalkeeps only those with the classexternal.:hoverkeeps only those under the pointer.::aftertargets generated content placed after the link's own content.
You can stack pseudo-classes, as in input:required:invalid. You cannot put anything after a pseudo-element, so a::after:hover is not the pattern to use. A few pseudo-elements do allow certain pseudo-classes after them, but that is a special case and rarely needed.
Edge cases to know early
A space changes the meaning
A pseudo-class attaches to whatever comes right before it. If you leave out the element, the selector applies to anything.
.card:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
.card :hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}The first rule styles the card when the pointer is over it. The second has a space before :hover. It is the same as .card *:hover, so it styles any descendant inside the card when the pointer is over that descendant. A stray space is a common bug.
One unknown pseudo selector can drop the whole rule
In an ordinary selector list, if the browser does not recognize one selector, it ignores the entire rule. This applies even when the other selectors in the list are valid.
/* If a browser does not know :future-state, it ignores the whole rule,
including the valid a:hover selector. */
a:hover,
a:future-state {
color: #c00;
}If you want a fallback for newer features, write them as separate rules. Some pseudo-classes, :is() and :where(), forgive unknown entries in their own argument lists. Their chapter explains this.
Pseudo-classes are live
The browser re-checks pseudo-classes as things change. A rule using :hover or :checked starts applying the moment the state begins and stops when it ends. You do not write any JavaScript for this. Pseudo-elements are different. They do not track a state. They exist as long as their originating element exists.
Pseudo selectors add to specificity
Specificity is the score that decides which rule wins when two rules target the same element. Pseudo-classes score like class selectors. Pseudo-elements score like type selectors. A rule such as a:hover therefore beats a bare a rule. The specificity chapter covers how to calculate the score and how :where() and :is() behave differently.
Try it
Save this file as pseudo-intro.html and open it in a browser. Hover over the link and the paragraph, and watch what each rule does.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Pseudo selectors: first look</title>
<style>
p.intro { margin: 1em 0; }
/* Plain selector: matches by what the HTML says */
p.intro { color: #333; }
/* Pseudo-class: same element, filtered by state */
p.intro:hover { background: #fff7d6; }
/* Pseudo-element: a part of the element, not the element */
p.intro::first-letter {
font-size: 2em;
color: #1a73e8;
}
/* Pseudo-element with generated content */
a.external::after { content: " \2197"; }
</style>
</head>
<body>
<p class="intro">Pseudo selectors let CSS react to state and reach parts of an element.</p>
<p><a class="external" href="https://developer.mozilla.org/">MDN Web Docs</a></p>
</body>
</html>The paragraph gets a pale background only while the pointer is over it. Its first letter is larger and blue at all times. The arrow after the link does not exist in the HTML. The browser draws it from the CSS.
Exercise
Look at the selector .menu li:first-child::before. Name each part and say whether it is a class selector, a type selector, a pseudo-class, or a pseudo-element. Then say what the selector targets.
Show answer
.menu is a class selector. li is a type selector, joined to .menu by a descendant combinator (the space). :first-child is a pseudo-class, because it has one colon and filters by position. ::before is a pseudo-element, because it has two colons and targets generated content. Together, the selector targets generated content placed before the content of each <li> that is the first child of its parent and sits inside an element with the class menu.
Exercise
A teammate writes .card :hover { outline: 2px solid #1a73e8; } and wants an outline on the card itself when the pointer is over it. The outline appears on elements inside the card instead. What is wrong, and what is the fix?
Show answer
The space before :hover makes the selector mean .card *:hover, which matches descendants of the card. Remove the space and write .card:hover { outline: 2px solid #1a73e8; }. Now :hover attaches directly to .card.