Practical :has() Patterns
You'll learn how to apply :has() to real-world design challenges like styling cards with images, highlighting forms with errors, and creating conditional layouts.
Now that you understand :has() as the parent selector, let's put it to work solving common UI problems you'll encounter constantly.
Styling Cards with Images
You can style a card differently based on whether it contains an image:
/* Card with an image gets different spacing */
.card:has(img) {
padding: 0;
}
.card:has(img) .card-content {
padding: 1rem;
}
/* Card without an image keeps uniform padding */
.card {
padding: 1rem;
}
This pattern lets cards adapt automatically without adding classes manually.
Forms with Errors
Highlight an entire form section when it contains invalid inputs:
/* Style the form group if it has an invalid input */
.form-group:has(input:invalid) {
border-left: 3px solid red;
background-color: #fff5f5;
}
.form-group:has(input:invalid) label {
color: red;
}
The form group responds to its children's validation state—no JavaScript needed.
Conditional Layouts
Adjust layouts based on content presence:
/* If sidebar has content, apply two-column layout */
.page-wrapper:has(.sidebar:not(:empty)) {
display: grid;
grid-template-columns: 250px 1fr;
}
/* Expand header if it contains navigation */
.header:has(nav) {
min-height: 80px;
}
Think of :has() as giving parents "awareness" of their children, allowing them to react accordingly—like a parent adjusting plans based on how many kids show up.
Key Takeaway: Use :has() to create adaptive components that style themselves based on their content—cards with/without images, forms with errors, and conditional layouts become self-managing without extra classes or JavaScript.