snippetcssModeratepending
CSS has() selector — parent selector and conditional styling
Viewed 0 times
has()parent selectorrelational selectorconditional CSSmodern CSS
browser
Problem
Need to style a parent based on its children, or style an element based on the state of a sibling. Previously impossible in CSS without JavaScript. The 'parent selector' was the most requested CSS feature for decades.
Solution
The :has() selector enables selecting elements based on their descendants, following siblings, or any relational condition.
Code Snippets
Parent selector and conditional styling with :has()
/* Style parent based on child state */
.card:has(img) {
/* Card with an image gets different layout */
grid-template-rows: 200px auto;
}
.card:has(:focus-visible) {
/* Highlight card when any child is focused */
outline: 2px solid var(--accent);
}
/* Form validation styling */
.field:has(input:invalid) {
/* Style the wrapper when input is invalid */
border-color: red;
}
.field:has(input:invalid) .error-message {
display: block;
}
/* Conditional layout */
.grid:has(> :nth-child(4)) {
/* Switch to 2-column when 4+ items */
grid-template-columns: 1fr 1fr;
}
/* Style preceding sibling (with + combinator) */
h2:has(+ p) {
/* h2 followed by p gets less margin */
margin-bottom: 0.5rem;
}
/* Page-level conditional styling */
body:has(.modal[open]) {
overflow: hidden;
}
body:has(#dark-toggle:checked) {
--bg: #1a1a1a;
--text: #f0f0f0;
}Revisions (0)
No revisions yet.