The parent selector in CSS
:has() finally lets a rule depend on what an element contains.
/* a card that contains an image gets a different layout */
.card:has(img) {
display: grid;
grid-template-columns: 8rem 1fr;
}
/* the field, styled from the state of the input inside it */
.field:has(input:invalid) { border-inline-start: 3px solid #dc2626; }
.field:has(input:focus-visible) { background: #f8fafc; }
/* a form with nothing filled in yet */
form:has(input:not(:placeholder-shown)) .actions { opacity: 1; }
/* the sibling case: a heading followed by a figure */
h2:has(+ figure) { margin-block-end: 0.5rem; }
How it works
:has()matches the outer element, not the thing inside it.- It reads forwards: a label that has an invalid input inside it.
- Its specificity is that of its most specific argument.
Keywords and builtins used here
actionsbackgroundcarddisplayfieldgridopacitypxrem
The run, in numbers
- Lines
- 15
- Characters to type
- 525
- Tokens
- 91
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 64 seconds.
Step 1 of 3 in Selectors that ask questions, step 8 of 21 in Responsive & modern CSS.