Sub topic 6
Pseudo-classes
This chapter assumes you can write type, class, and ID selectors, know the basic CSS rule syntax, and have read the chapters on attribute selectors and combinators. A pseudo-class lets you select elements by their state or position, not by their name, class, or attributes. This chapter covers the common groups, how they affect specificity, and the errors that trip people up.
What a pseudo-class is
A pseudo-class is a keyword that starts with a single colon and attaches to a selector. It matches an element only when that element is in a certain condition. The browser decides the condition. You do not add a class to the HTML.
a:hover { text-decoration: underline; }
li:first-child { font-weight: bold; }
input:disabled { opacity: 0.5; }Each rule applies only while its condition is true. When the user moves the pointer away from the link, a:hover stops matching and the underline goes away.
A pseudo-class is not a pseudo-element. Pseudo-classes use one colon and select existing elements in a given state. Pseudo-elements use two colons and select a part of an element, such as ::before. The next chapter covers pseudo-elements.
Specificity of pseudo-classes
A pseudo-class counts in the middle column of the specificity triple, the same as a class or an attribute selector. This is the key fact for the cascade.
| Selector | Specificity (IDs, classes, types) |
|---|---|
| `a` | (0,0,1) |
| `a:hover` | (0,1,1) |
| `.link` | (0,1,0) |
| `.link:hover` | (0,2,0) |
| `a:not(.x):hover` | (0,2,1) |
So a:hover (0,1,1) beats a plain .link rule only if types break the tie. Both have one class-level part, and a:hover also has one type. It therefore wins (0,1,1) against (0,1,0). A rule that sets a { color: red; } can never override a:hover, because a type selector is weaker than any class-level selector.
Link and user-action states
These pseudo-classes respond to what the user is doing or has done.
:linkmatches links that have not been visited.:visitedmatches links the user has visited.:hovermatches while a pointing device is over the element.:activematches while the element is being pressed.:focusmatches the element that has keyboard focus.:focus-visiblematches focus only when the browser decides a focus indicator is helpful, such as keyboard navigation.:focus-withinmatches an element when it or any descendant has focus.
The LVHA order
All of these have the same specificity, so source order decides between them. If a link is both visited and hovered, both rules match, and the later one wins. Write them in this order:
a:link { color: royalblue; }
a:visited { color: purple; }
a:hover { color: crimson; }
a:active { color: darkred; }The order is link, visited, hover, active. A common mistake is putting a:hover before a:visited. Then a visited link never shows the hover color, because the :visited rule comes later and wins the tie.
Privacy limits on :visited
Browsers restrict :visited so that pages cannot learn a visitor's history. You can change color-related properties such as color, background-color, and border-color. You cannot change layout properties such as width or margin, and the browser reports the unvisited values to scripts.
Focus styles
Use :focus-visible to show a focus ring for keyboard users without showing it after a mouse click on a button.
button:focus-visible {
outline: 3px solid #1a73e8;
outline-offset: 2px;
}Removing the outline with outline: none and giving nothing in return makes the page hard to use with a keyboard. Replace the outline instead of deleting it.
Structural pseudo-classes
These select by position in the document tree.
| Pseudo-class | Matches |
|---|---|
| `:first-child` | An element that is the first child of its parent |
| `:last-child` | An element that is the last child of its parent |
| `:only-child` | An element with no siblings |
| `:nth-child(n)` | The element at position n among all siblings |
| `:nth-of-type(n)` | The element at position n among siblings of the same type |
| `:empty` | An element with no children and no text |
| `:root` | The top element of the document, `html` in HTML |
The nth forms accept a number, the keywords odd and even, or a formula an+b. Here n counts from 0, so 2n+1 matches positions 1, 3, 5, and so on.
tr:nth-child(even) { background: #f3f3f3; }
li:nth-child(3n+1) { color: teal; }
li:nth-last-child(-n+2) { font-weight: bold; }The last rule selects the final two items. The formula -n+2 gives 2, 1, 0 as n increases, so it matches positions 2 and 1 counting from the end.
nth-child versus nth-of-type
:nth-child counts every sibling regardless of its tag. :nth-of-type counts only siblings with the same tag name. Consider this HTML:
<div>
<h2>Title</h2>
<p>First</p>
<p>Second</p>
</div>p:nth-child(2) matches the first paragraph, because it is the second child of the div. p:nth-of-type(2) matches the second paragraph, because it is the second p. In the first selector, p is only a filter: the element must be the second child and also a p.
In CSS Selectors Level 4, :nth-child(2 of .item) lets you count only siblings that match a selector list. Check browser support before relying on it.
Whitespace nodes and :empty
:empty does not match an element that contains a space or a line break, in most browsers. <div> </div> is not empty in that sense. Comments do not count as content, so <div><!-- x --></div> still matches.
Form and input state pseudo-classes
These reflect the state of form controls.
:checkedmatches checked checkboxes, radio buttons, and selected options.:disabledand:enabledmatch controls by whether they can be used.:requiredand:optionalmatch by therequiredattribute.:validand:invalidmatch by constraint validation.:placeholder-shownmatches an input that currently displays its placeholder.:user-invalidmatches an invalid control only after the user has interacted with it.
input:invalid { border-color: crimson; }
input:placeholder-shown { border-color: #bbb; }
input:checked + label { font-weight: bold; }A gotcha with :invalid: an empty required field is invalid from the moment the page loads, so the error style shows before the user types anything. :user-invalid avoids this where supported. A common fallback is to combine :invalid with :not(:placeholder-shown), which waits until the field holds a value.
Negation and functional pseudo-classes
:not() matches elements that do not match its argument. :is() and :where() match any element in a selector list. These take the specificity rules from the later chapter, but the main point is this: :is() and :not() use the most specific argument, and :where() always counts as zero.
p:not(.hidden) { color: blue; } /* (0,1,1) */
:is(h1, h2, h3):hover { color: red; } /* (0,1,1) */The pseudo-class :has() selects an element based on what it contains. It also counts as its most specific argument.
.card:has(img) { padding: 0; }
label:has(input:checked) { font-weight: bold; }.card:has(img) styles a card that contains an image. Before :has(), CSS could not select a parent based on its children.
Stacking and combining
You can chain pseudo-classes on one element. Each adds to specificity.
a:not([href]):hover { cursor: default; }
li:first-child:last-child { list-style: none; }The second rule is the same as li:only-child, with higher specificity (0,2,1). Prefer the single pseudo-class when one exists.
Common errors
- Wrong order of link states. Fix by following link, visited, hover, active.
- Expecting
:nth-childto count a type. Use:nth-of-typewhen you want to count tags. - Writing a space before the colon.
a :hovermeans "any element in:hoverstate inside ana", because the space is a descendant combinator and the omitted type becomes*. Writea:hoverfor the link itself. - Using
:hoveras the only way to reveal content. Touch screens have no true hover, and keyboard users never trigger it. Pair it with:focus-visibleor:focus-within. - Writing
:first-childand expecting the first of a kind. It matches only if the element is the first child of all. - Misspelled pseudo-classes in a list. In a selector list, one invalid selector can make the whole rule invalid and ignored. Use
:is(), which forgives invalid arguments, when mixing selectors with uneven support.
Exercise
Given the HTML <ul><li>A</li><li>B</li><li>C</li></ul>, which items does li:nth-child(odd):not(:last-child) match, and what is its specificity?
Show answer
It matches only A. A and C are odd, but C is the last child and is excluded by :not(:last-child). Specificity is (0,2,1): :nth-child adds one class-level part, :not(:last-child) takes the specificity of its argument and adds one more, and li adds one type.
Exercise
A stylesheet has a:hover { color: red; } followed by a:visited { color: purple; }. A visited link is hovered. What color does it show, and how do you fix it?
Show answer
It shows purple. Both rules have specificity (0,1,1), so the later rule, a:visited, wins. Move a:hover after a:visited so the order is link, visited, hover, active.