Sub topic 16
Practical patterns and common pitfalls
This chapter pulls the earlier pieces together. It assumes you know pseudo-class and pseudo-element syntax, the focus and form state selectors, the logical selectors :is(), :where(), :not() and :has(), and how specificity is counted. Here you will use them in four reusable patterns, then go through the mistakes that cause most "my selector does nothing" bugs.
Pattern 1: A table that responds to the user
A data table often needs zebra striping, a hover highlight, and a visible cue when a row contains a focused control. Each state is a separate rule, so keep them in an order that lets the interactive states win.
tbody tr:nth-child(even) {
background: #f5f5f5;
}
@media (hover: hover) {
tbody tr:hover {
background: #e8f0fe;
}
}
tbody tr:focus-within {
outline: 2px solid #1a73e8;
outline-offset: -2px;
}Three details matter here:
- The hover rule has the same specificity as the zebra rule, so it wins only because it comes later.
- The
@media (hover: hover)wrapper limits hover styling to devices with a real pointer. On touch screens,:hoveroften sticks after a tap, so a row can stay highlighted. :focus-withinis on the row, not the cell. The outline appears whenever any link or button inside the row has focus.
Pattern 2: Form feedback that waits for the user
Showing a red border on an empty required field before anyone has typed is a common annoyance. Combine the validity state with :placeholder-shown, which is true only while the placeholder is visible.
<label class="field">
<span>Email</span>
<input type="email" required placeholder=" ">
</label>.field input:required:invalid:not(:placeholder-shown) {
border-color: #c00;
}
.field:has(input:required) span::after {
content: " *";
color: #c00;
}
.field input:disabled {
opacity: 0.5;
}The placeholder is a single space. The input needs a placeholder attribute for :placeholder-shown to work, but the space keeps the field looking empty.
The second rule uses :has() on the label to add an asterisk through ::after when its input is required. The asterisk is only decoration. The required attribute is what tells assistive technology the field is mandatory.
Newer browsers also support :user-invalid, which matches only after the user has interacted with the field. Where you can rely on it, it replaces the :not(:placeholder-shown) workaround. Check browser support before you drop the older pattern.
Pattern 3: Separators without extra markup
Use position and negation together to put a divider between list items. This avoids a stray line after the last item.
.breadcrumb li:not(:last-child)::after {
content: "/";
margin-inline: 0.5em;
color: #767676;
}
.menu li + li {
border-top: 1px solid #ddd;
}Both rules give the same visual result for borders, but they differ in other ways. The ::after version produces a character, which is why it should be purely decorative. The li + li version uses the adjacent sibling combinator and needs no pseudo-class at all. If a plain combinator does the job, prefer it.
Pattern 4: A card that adapts to its content
:has() lets a parent change layout depending on its children, which used to require an extra class added by script or by the template.
.card {
display: block;
}
.card:has(> img) {
display: grid;
grid-template-columns: 8rem 1fr;
gap: 1rem;
}
.card:has(:focus-visible) {
box-shadow: 0 0 0 3px #1a73e8;
}The child combinator in :has(> img) limits the match to a direct child image. Without it, an image anywhere inside the card would trigger the layout. The last rule is similar to :focus-within, but :has(:focus-visible) highlights the card only when the browser would show a focus ring, so mouse clicks do not trigger it.
Pitfalls
Why a selector does nothing
Work through the checks in this order when a pseudo selector has no effect.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `.card::before` with no `content` | The box is never generated | Add `content: ""` |
| `input::after` or `img::before` | Replaced elements and most form controls do not generate these boxes | Style a wrapper element instead |
| `a::after:hover` | Invalid. The pseudo-element must come last | Write `a:hover::after` |
| Mixing a vendor selector in a list, such as `::placeholder, ::-webkit-input-placeholder` | A browser that does not recognise one selector drops the whole rule | Use separate rules |
| `.item:nth-child(2)` expecting the second `.item` | Matches only if the second child of the parent is also an `.item` | Use `:nth-of-type()`, or restructure |
| `outline: none` on `:focus` with no replacement | Keyboard users lose their position | Style `:focus-visible` instead |
| Placing `a:hover` before `a:link` | The hover style is overridden | Keep the link, visited, hover, active order |
The vendor-prefix row is worth remembering. A selector list is normally all-or-nothing: one invalid selector invalidates the entire rule. The exceptions are :is() and :where(), which ignore invalid selectors in their arguments.
Position counting is by siblings, not by class
:nth-child() counts every element sibling, then checks the other conditions. Consider this markup.
<div class="post">
<h2>Title</h2>
<p class="note">First</p>
<p class="note">Second</p>
</div>.note:nth-child(2) matches "First", because it is the second child of the div and it has the class. p:nth-of-type(2) matches "Second", because it counts only p elements. Neither counts by class. If you need "the second element with this class", no single selector does it. Change the markup or use :nth-child(2 of .note) where the browser supports it.
Specificity surprises
Pseudo-classes count like classes, and pseudo-elements count like type selectors. :is() and :not() take the specificity of their most specific argument, and :where() always contributes zero.
| Selector | Specificity (IDs, classes, types) |
|---|---|
| `a:hover` | 0, 1, 1 |
| `.nav a:not(.active):hover` | 0, 3, 1 |
| `.card::before` | 0, 1, 1 |
| `:is(#main, .page) p` | 1, 0, 1 |
| `:where(#main, .page) p` | 0, 0, 1 |
The fourth row shows a trap. :is() takes the ID's weight even when the matched element has only the class. Use :where() for reset and base styles that later rules should be able to override easily.
Accessibility and generated content
Treat the following as a review checklist.
- Keep a visible focus indicator on every interactive element, with at least 3:1 contrast against its surroundings.
- Do not put meaningful text in
content. Screen reader support for generated text is inconsistent, and users cannot select or translate it reliably. - Do not signal state by color alone. Pair a red border on an invalid field with an error message in the markup.
- Check
::selectionand::placeholdercolors for contrast. A placeholder lighter than#767676on white fails the 4.5:1 text contrast ratio.
Putting it together
When you add a pseudo selector, ask four questions: Is it a state, a position, or a part of the element? Does it need a media query for device support? Does it keep the interface usable without a mouse? Will it be easy to override later? Answering these before you write the rule avoids most of the problems above.
Exercise
Given the markup <div><h2>Title</h2><p class="note">A</p><p class="note">B</p></div>, which paragraph does .note:nth-child(2) select, and which does p:nth-of-type(2) select? Then explain why .tag::before { color: red; } shows nothing.
Show answer
.note:nth-child(2) selects "A", because the h2 is child 1, "A" is child 2, and it has the class note. p:nth-of-type(2) selects "B", because it counts only p siblings. .tag::before { color: red; } shows nothing because a ::before box is generated only when content is set to something other than none. Adding content: "" creates the box.
Exercise
Write a rule that gives a text input a red border only when it is required, invalid, and not showing its placeholder. State what the input needs in its markup for the rule to work.
Show answer
input:required:invalid:not(:placeholder-shown) { border-color: #c00; }. The input needs a placeholder attribute (for example placeholder=" "). Without one, :placeholder-shown never matches, so the :not() always passes and the red border appears immediately on an empty field.