The :has() pseudo-class is a modern relational selector used to style elements based on their children or internal content.
It is often called:
[code theme="dark"] Parent Selector [/code]because it allows CSS to target parent elements depending on what they contain.
Before:
[code theme="dark"] :has() [/code]developers usually needed JavaScript for parent-based styling.
Now modern CSS can handle many dynamic UI interactions without JavaScript.
Styles only cards that contain an image.
| Selector | CSS | Live Demo |
|---|---|---|
| .card:has(img) | [code theme="dark"] .card:has(img){ border:2px solid blue; } [/code] |
Card Without Image
|
| .card:has(input:checked) | [code theme="dark"] .card:has(input:checked){ background:#dbeafe; } [/code] | |
| form:has(input:invalid) | [code theme="dark"] form:has(input:invalid){ border-color:red; } [/code] | |
| li:has(a.active) | [code theme="dark"] li:has(a.active){ font-weight:bold; } [/code] |
|
| .grid:has(.featured) | [code theme="dark"] .grid:has(.featured){ grid-template-columns:2fr 1fr; } [/code] |
Featured Item
Sidebar
|
| Feature | Traditional CSS | :has() |
|---|---|---|
| Parent Selection | Not Possible | Supported |
| JavaScript Dependency | Often Required | Reduced |
Since:
[code theme="dark"] :has() [/code]is a modern CSS selector, older browsers may not support it fully.
The :has() pseudo-class is considered one of the most powerful modern CSS selector features for dynamic UI styling.