如何用CSS选择器仅选中含.unit的.parent内的重要div元素?
The cleanest CSS fix for this scenario is leveraging the :has() pseudo-class—it lets us target a parent element based on the presence of specific children, which is perfect here since .unit comes after your target div. Here's how to implement it:
/* Style the "Important element" div only when .parent contains .unit */ .parent:has(.unit) span + div { /* Add your desired styles here */ background-color: #ffeb3b; padding: 4px 8px; border-radius: 4px; font-weight: 600; }
Breakdown of How This Works:
.parent:has(.unit): This selects any.parentcontainer that contains a.unitelement (regardless of where.unitis placed inside the parent).span + div: This targets the<div>that is the immediate next sibling of the<span>inside the qualifying.parent—which is exactly your "Important element" div.
If you prefer to target the div by its position among direct children (instead of relying on the preceding span), you can use this alternative selector:
.parent:has(.unit) > div:nth-child(2) { /* Same styles as above */ }
This works because the "Important element" div is always the second direct child of .parent (right after the span).
Browser Support
The :has() pseudo-class is supported in all modern browsers:
- Chrome/Edge: Supported since version 105
- Firefox: Supported since version 121
- Safari: Supported since version 15.4
For older browser support (like Firefox pre-121), you can use a simple JavaScript fallback:
// Add a custom class to .parent if it contains .unit document.querySelectorAll('.parent').forEach(parent => { if (parent.querySelector('.unit')) { parent.classList.add('has-unit'); } });
Then style using the custom class:
.parent.has-unit span + div { /* Your styles */ }
内容的提问来源于stack exchange,提问作者Dirk Albrecht

