css selectors modern-css

The CSS :has() Selector

The `:has()` selector lets you style a parent based on what's inside it. This was impossible with CSS alone until now.

Want to highlight a card only when it contains an image? Style a form when an input is focused? `:has()` makes it simple.

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

/* Highlight label when its input is focused */
label:has(input:focus) {
  color: blue;
}

/* Style form when any input is invalid */
form:has(input:invalid) {
  border-color: red;
}
100 Coding for Website Design Tips

This tip is from

100 Coding for Website Design Tips

99 more tips like this one.

Get the Book