Sub topic 2
Looking Ahead with CSS `:has()`
Assume you know basic selectors, combinators, pseudo-classes, the cascade, and specificity. The :has() pseudo-class is a relational selector: it selects an element when a relative selector matches something connected to that element.
Looking ahead: siblings and previous-sibling selection
A relative selector can begin with a sibling combinator. The + combinator means “immediately following sibling.” The ~ combinator means “any following sibling.”
h2:has(+ p) {
margin-block-end: 0.25rem;
}
h2:has(~ ul) {
color: rebeccapurple;
}The first rule selects an h2 immediately followed by a p. The second selects an h2 when a later sibling is a ul. In effect, CSS can style an earlier sibling based on what comes after it.
How specific is `:has()`?
The specificity of :has() equals the specificity of its most specific argument. Add that value to the rest of the selector.
.card:has(#featured) { } /* (1, 1, 0) */
.a:has(.b, p) { } /* (0, 2, 0) */The ID in the first argument contributes an ID value. In the second rule, .b is more specific than p, so the argument contributes one class value.
Combining `:has()` with `:not()` and `:is()`
These pseudo-classes also use the most specific argument in their selector list.
.card:not(:has(img)) {
padding: 2rem;
}
.card:has(:not(img)) {
border: 1px solid #ccc;
}
.card:has(:is(img, video)) {
display: grid;
}The first rule matches cards without an image. The second matches cards containing a descendant that is not an image. The third matches cards containing either an image or a video.
Reacting to state with `:has()`
State pseudo-classes can style a wrapper based on its control.
.field:has(input:focus-visible) {
outline: 2px solid royalblue;
}
.field:has(input:invalid:not(:placeholder-shown)) label {
color: crimson;
}These rules react to keyboard focus and visible invalid input without JavaScript.
Exercise
Which selector selects an h2 immediately followed by a paragraph?
Show answer
h2:has(+ p)