Intermediate LevelCSS & Modern Layouts
How does the CSS :has() pseudo-class work as a parent/relational selector?
❓ Interview Prompt: Explain :has() selector syntax, how it selects parents based on children, and practical use cases.
The :has() pseudo-class is the long-awaited parent selector in CSS. It selects an element only if it contains a descendant matching the argument:
Syntax:
selector:has(child-selector) { /* styles */ }
Use Cases:
1
Style parent based on child state:
.form-group:has(:invalid) — highlight form groups containing invalid inputs.2
Conditional layout:
.card:has(img) — cards with images get different padding.3
Sibling awareness:
h2:has(+ p) — style h2 only if immediately followed by a paragraph.4
State-dependent global styling:
html:has(.modal-open) — prevent body scroll when modal is open.Code Implementation Example
css
/* Cards with images get zero top padding */
.card:has(img) { padding-top: 0; }
/* Form groups with invalid inputs show red border */
.form-group:has(:invalid) {
border-left: 3px solid red;
padding-left: 12px;
}
/* Prevent scroll when modal is open */
html:has(.modal-open) { overflow: hidden; }
/* Style heading only if followed by a paragraph */
h2:has(+ p) { margin-bottom: 0.5rem; }💡Parent selection, form validation styling, and sibling-aware heading spacing.
🎯 Interview Key Takeaway
:has() eliminates JavaScript-dependent parent styling. It is the most powerful CSS selector addition since Flexbox.
#:has()#Parent Selector#Selectors#Intermediate
Back to all CSS & Modern Layouts Questions→