typestar

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

  1. :has() matches the outer element, not the thing inside it.
  2. It reads forwards: a label that has an invalid input inside it.
  3. Its specificity is that of its most specific argument.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Selectors that ask questions, step 8 of 21 in Responsive & modern CSS.

← Previous Next →