Back to TIL

CSS :has() selector is a game-changer for parent selection

css frontend

CSS finally has a parent selector with :has()! This was impossible for decades and now it’s widely supported.

/* Style a card differently if it contains an image */
.card:has(img) {
  padding: 0;
}

/* Style a form when an input is focused */
form:has(input:focus) {
  border-color: blue;
}

/* Style a label when its checkbox is checked */
label:has(input:checked) {
  font-weight: bold;
}

You can even select siblings:

/* Style a paragraph that comes before an image */
p:has(+ img) {
  margin-bottom: 0;
}

This eliminates so much JavaScript that we used to write just for conditional styling!