Sub topic 1
Styling a Parent from Its Children with `:has()`
Prerequisites
Assume you know basic CSS selectors, combinators such as >, +, and ~, common pseudo-classes, and basic specificity.
Styling a Parent from Its Children: What `:has()` Does
:has() is a relational pseudo-class. It matches an element when a related element exists inside it or after it. This lets CSS style a parent based on its contents without JavaScript.
For example, this rule selects every .card that contains an image at any depth:
.card:has(img) {
display: grid;
grid-template-columns: 200px 1fr;
gap: 1rem;
}A card without an image does not match. The browser checks each .card, then tests the selector inside :has().
How `:has()` Is Written
The general form is:
subject:has(relative-selector-list) {
/* declarations */
}The subject is the element you want to style. The argument is a relative selector list: one or more selectors evaluated in relation to that subject.
These selectors mean different things:
/* Any descendant image */
.card:has(img) {}
/* A direct child image */
.card:has(> img) {}
/* An immediately following paragraph */
h2:has(+ p) {}
/* Any following sibling list */
h2:has(~ ul) {}The combinator at the beginning of the argument controls the relationship. With no leading combinator, descendant matching is used.
:has() can contain a comma-separated list. The subject matches if at least one argument matches:
.card:has(img, video) {
border: 1px solid teal;
}Matching Descendants and Direct Children
Use :has(figure img) when the image may be nested inside a figure. Use :has(> img) when the image must be an immediate child.
figure:has(> figcaption) {
border-bottom: 2px solid currentColor;
}This selects only figures whose direct child is a figcaption. A caption nested inside another element does not satisfy the selector.
Exercise
What does .panel:has(> button) match?
Show answer
It matches panels with at least one button as a direct child. A button nested deeper inside another element does not count.