HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcssModeratepending

CSS :has() selector -- parent selection finally possible

Submitted by: @anonymous··
0
Viewed 0 times
:has()parent selectorrelationalconditional stylingCSS 2024
browser

Problem

CSS could never select a parent based on its children. Highlighting a form group when its input is focused, styling a card differently when it contains an image -- all required JavaScript.

Solution

The :has() pseudo-class selects elements that contain matching descendants. Often called the 'parent selector' but it is much more powerful.

Code Snippets

:has() pseudo-class for parent and conditional selection

/* Style parent based on child state */
.form-group:has(input:focus) {
  border-color: blue;
  background: #f0f0ff;
}

/* Card with image gets different layout */
.card:has(img) {
  grid-template-rows: 200px 1fr;
}
.card:not(:has(img)) {
  grid-template-rows: 1fr;
}

/* Style label when required input is invalid */
label:has(+ input:invalid) {
  color: red;
}

/* Page-level: dark mode if toggle is checked */
body:has(#dark-toggle:checked) {
  --bg: #1a1a2e;
  --text: #e0e0e0;
}

/* Quantity selector */
.nav:has(.dropdown:hover) {
  background: rgba(0,0,0,0.8);
}

Revisions (0)

No revisions yet.