Sub topic 4
Looking ahead: siblings and previous-sibling selection
This chapter assumes you know the four combinators (descendant, >, +, ~), how :hover and :invalid work, and the basic :has() syntax from the earlier chapters. Here you will use :has() with the two sibling combinators. The result is that CSS can style an element based on what comes after it, which was not possible before :has().
The direction problem
Ordinary sibling combinators only look forward. In h2 + p, the subject is the p, and the h2 is only a condition. CSS has no plain selector that styles the h2 because a p follows it.
:has() removes that limit. A relative selector inside :has() can begin with + or ~. It is resolved from the element the :has() is attached to, which is called the anchor. The anchor stays the subject of the whole selector. The sibling you describe is only a condition.
h2:has(+ p) {
margin-block-end: 0.25rem;
}
h2:has(~ ul) {
color: rebeccapurple;
}h2:has(+ p)matches anh2whose next element sibling is ap.h2:has(~ ul)matches anh2that has aulanywhere later among its siblings.
In both rules the h2 is styled. The p and ul are not.
The two sibling combinators inside :has()
Adjacent sibling: `:has(+ ...)`
The + combinator matches only the element sibling that comes immediately after the anchor. Text nodes and comments are ignored, so whitespace between tags does not matter. Another element in between does matter.
<h2>Intro</h2>
<p>First paragraph.</p>
<h2>Links</h2>
<hr>
<p>Paragraph after a rule.</p>With h2:has(+ p), the first h2 matches because a p follows it directly. The second does not, because an hr is in the way.
General sibling: `:has(~ ...)`
The ~ combinator matches any later sibling that fits. It never looks backward. Only siblings after the anchor count, so an h2 that comes after the ul would not match h2:has(~ ul).
| Selector | Matches the anchor when | Looks at |
|---|---|---|
| `h2:has(+ p)` | the very next element sibling is a `p` | one element |
| `h2:has(~ p)` | any later sibling is a `p` | all later siblings |
| `h2:has(+ p + ul)` | a `p` follows, then a `ul` immediately after it | a chain |
| `h2:has(+ p ~ ul)` | a `p` follows, and a `ul` comes anywhere after that `p` | a mixed chain |
You can chain combinators inside the argument, as in the last two rows. The chain starts at the anchor and moves forward. Everything after the first combinator is a condition on other elements, and the anchor is still the one styled.
Selecting the previous sibling
"Select the previous sibling" is the same technique seen from the other end. If you want to style element A because element B comes right after it, put :has(+ B) on A.
Suppose you want a label to look different when the input right after it is required.
<label for="email">Email</label>
<input id="email" type="email" required>label:has(+ input:required)::after {
content: " *";
color: crimson;
}The label is the subject, so it receives the ::after content. Here the pseudo-element sits outside :has(), which is allowed. Pseudo-elements cannot go inside the :has() argument, and a later chapter covers that restriction.
The ~ form selects every earlier sibling that has a match somewhere after it. That makes a "styled up to the current item" pattern possible without JavaScript. A rating widget is a good example.
<div class="stars">
<span class="star"></span>
<span class="star"></span>
<span class="star"></span>
<span class="star"></span>
<span class="star"></span>
</div>.star {
display: inline-block;
width: 1.5rem;
height: 1.5rem;
background: #ccc;
clip-path: polygon(50% 0, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);
}
/* The hovered star */
.star:hover,
/* Every star before it */
.star:has(~ .star:hover) {
background: gold;
}The second selector reads: a .star that has a later sibling .star in the :hover state. Hovering the fourth star lights stars one to four. Stars after the hovered one are untouched.
Neighbor effects: styling both sides of a hovered item
Combining + with :has() lets you affect the item before a hovered one. Combining it with a plain + affects the item after. Together they create a "dock" effect.
<ul class="dock">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>.dock {
display: flex;
gap: 0.5rem;
list-style: none;
padding: 0;
align-items: end;
}
.dock li {
padding: 0.5rem 1rem;
background: #eee;
transition: transform 150ms;
}
.dock li:hover {
transform: scale(1.4);
}
/* Immediate neighbors */
.dock li:has(+ li:hover),
.dock li:hover + li {
transform: scale(1.2);
}The first selector is the previous-sibling case, and the second is the ordinary next-sibling case. Both are written from the point of view of the neighbor you want to change.
Reading sibling selectors correctly
A selector with :has(+ ...) is easy to misread, so use this checklist.
- Find the compound selector that holds
:has(). That compound selector, for exampleh2, is the subject. - Read inside the parentheses as a relative selector that starts at the subject.
- Treat every element named inside the parentheses as a condition, never as a target.
- If you need to style the later sibling, write a plain sibling selector from the other direction, such as
h2 + p.
You can combine both views. This rule styles an h2 that is followed by a p, and separately styles that p:
h2:has(+ p) {
border-inline-start: 4px solid steelblue;
}
h2 + p {
font-style: italic;
}Edge cases and gotchas
Only element siblings count
+ skips text nodes. The text between two tags is invisible to it. Elements hidden with display: none still exist in the DOM, so they still count as siblings. A hidden div between an h2 and a p breaks h2:has(+ p).
Order in the DOM, not on screen
Sibling combinators follow source order. If you reorder items with flex-direction: row-reverse or the order property, :has(+ ...) still follows the DOM. A "previous" item in the DOM may appear to the right on screen.
.row {
display: flex;
flex-direction: row-reverse;
}
/* Still based on DOM order: the li that precedes a hovered li in the HTML */
.row li:has(+ li:hover) {
background: khaki;
}On screen, the highlighted item sits to the right of the hovered one. The selector is correct, but it does not match what you see.
The anchor can match without the target changing
h2:has(~ ul) does not tell you which ul matched. If a style depends on that specific list, use a selector where the list is the subject.
Dynamic changes are tracked
The browser re-evaluates the selector when the DOM or state changes. If a ul is inserted after the h2, the style applies immediately. If the ul is removed, the style goes away. No script needs to toggle a class.
A complete example
This page combines the ideas. A heading gets an accent when it has a paragraph right after it, a different style when a list comes later, and each form label reacts to the input after it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sibling :has() demo</title>
<style>
h2:has(+ p) {
border-inline-start: 4px solid steelblue;
padding-inline-start: 0.5rem;
}
h2:has(~ ul) {
color: rebeccapurple;
}
label:has(+ input:invalid:not(:placeholder-shown)) {
color: crimson;
}
</style>
</head>
<body>
<h2>Overview</h2>
<p>This heading is followed by a paragraph and later by a list.</p>
<ul>
<li>Alpha</li>
<li>Beta</li>
</ul>
<form>
<label for="age">Age (18 or more)</label>
<input id="age" type="number" min="18" placeholder=" ">
</form>
</body>
</html>Open the file in a browser that supports :has() and type 10 into the number field. The label turns crimson because the input after it is invalid and no longer shows its placeholder.
Summary of the technique
- Put
+or~at the start of the:has()argument to look at later siblings. - The element carrying
:has()is always the one styled. - To style an earlier sibling, make it the anchor and describe the later sibling inside
:has(). - Sibling matching follows DOM order, ignores text nodes, and counts hidden elements.
Exercise
Write one selector that colors the <li> elements that come before the <li class="current"> in the same list, but not the current item and not the ones after it. Then explain why li:has(+ .current) is not enough.
Show answer
Use li:has(~ li.current). The ~ combinator matches any later sibling, so every li that has li.current somewhere after it matches, and the current item and later items do not. li:has(+ .current) uses the adjacent combinator, so it matches only the single li immediately before the current one.
Exercise
Given this markup, which elements does h3:has(+ p) match? Which does h3:has(~ p) match?
<h3>A</h3><p>x</p>
<h3>B</h3><div>y</div><p>z</p>
<h3>C</h3><div>w</div>
Show answer
h3:has(+ p) matches only A, because only A has a p as its immediate next element sibling. h3:has(~ p) matches A and B. A has p after it, and B has a p later among its siblings, even though a div sits between them. C has no p after it, so it matches neither selector. (Note: h3:has(~ p) also looks past the next h3, so A and B both match because of the paragraphs that follow.)
Exercise
A flex row uses flex-direction: row-reverse. You write li:has(+ li:hover) to highlight the item to the left of a hovered item on screen. Why does it highlight the wrong side, and how do you fix it?
Show answer
Sibling combinators follow DOM order, not visual order. With row-reverse, the item before the hovered one in the HTML appears to its right on screen. To highlight the item on the left on screen, which comes after the hovered one in the DOM, use the ordinary combinator li:hover + li.