tezvyn:

Styling a parent with the :has() selector

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

understanding of relational selection.

OUTLINE

:has() matches an element that contains or relates to a given selector, enabling upward styling; figure:has(figcaption) targets captioned figures.

WHAT THIS TESTS: This checks that you grasp relational selection: matching an element by what it contains or what follows it, and that the subject of the rule is the outer element.

A GOOD ANSWER COVERS: The :has() pseudo-class accepts a relative selector list and matches its subject element when at least one of those relative selectors matches. So figure:has(figcaption) matches any figure that contains a figcaption, and the declarations apply to the figure, not the caption. This is genuinely a parent or ancestor selector, and combined with combinators it can express following-sibling and other relationships, for example label:has(+ input:required). Because the subject is the left-most compound, you decide which element gets styled. It enables patterns like highlighting a form group that contains an invalid field, or laying out a card differently when it has an image.

COMMON WRONG ANSWERS: Believing the styles land on the inner element named inside :has(); they land on the subject before it. Thinking :has() only matches direct children; it accepts full relative selectors with descendant and sibling combinators. Assuming it is the same as :is() or :where(), which select among the listed selectors rather than testing a relationship.

LIKELY FOLLOW-UPS: How does :has() compute specificity (like :is(), the most specific argument). Can you chain or nest :has(). What are the performance trade-offs on large, frequently mutated trees.

ONE CONCRETE EXAMPLE: figure:has(figcaption) { display: grid; gap: 8px; border: 1px solid #ccc; } styles only figures that include a caption, giving them a tidy framed layout, while uncaptioned figures keep their default appearance with no extra wrapper element or JavaScript.

Read the original → developer.mozilla.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.