snippetcssModeratepending
CSS :has() selector for parent-based styling
Viewed 0 times
hasparent-selectorrelationalpseudo-classconditional
Problem
CSS could only select downward (parent to child). Need to style a parent based on what children it contains.
Solution
Use :has() to select parents based on children:
/ Style card differently if it has an image /
.card:has(img) {
grid-template-rows: 200px 1fr;
}
.card:not(:has(img)) {
grid-template-rows: 1fr;
}
/ Style form when it has invalid inputs /
form:has(:invalid) {
border: 2px solid red;
}
/ Style label when its input is focused /
label:has(+ input:focus) {
color: blue;
font-weight: bold;
}
/ Sibling selector: style element if next sibling exists /
h2:has(+ p) {
margin-bottom: 0.5rem; / Tighter spacing when followed by p /
}
/ Count-based styling /
ul:has(li:nth-child(5)) {
columns: 2; / Multi-column if 5+ items /
}
/ Dark mode for specific sections /
.page:has(.dark-widget) {
--bg: #1a1a1a;
}
/ Hide empty containers /
.container:not(:has(*)) {
display: none;
}
/ :has() can replace many JavaScript toggles! /
/ Supported in all modern browsers (Chrome 105+, Safari 15.4+, Firefox 121+) /
/ Style card differently if it has an image /
.card:has(img) {
grid-template-rows: 200px 1fr;
}
.card:not(:has(img)) {
grid-template-rows: 1fr;
}
/ Style form when it has invalid inputs /
form:has(:invalid) {
border: 2px solid red;
}
/ Style label when its input is focused /
label:has(+ input:focus) {
color: blue;
font-weight: bold;
}
/ Sibling selector: style element if next sibling exists /
h2:has(+ p) {
margin-bottom: 0.5rem; / Tighter spacing when followed by p /
}
/ Count-based styling /
ul:has(li:nth-child(5)) {
columns: 2; / Multi-column if 5+ items /
}
/ Dark mode for specific sections /
.page:has(.dark-widget) {
--bg: #1a1a1a;
}
/ Hide empty containers /
.container:not(:has(*)) {
display: none;
}
/ :has() can replace many JavaScript toggles! /
/ Supported in all modern browsers (Chrome 105+, Safari 15.4+, Firefox 121+) /
Why
:has() is the most powerful CSS selector addition in years. It enables parent selection, previously impossible without JavaScript.
Revisions (0)
No revisions yet.