Does parent selector exist in CSS?
P粉713866425
2023-08-21 10:43:42
<p>How do I select the <code><li></code> element that is the direct parent of the anchor element? </p>
<p>For example, my CSS might look like this:</p>
<pre class="brush:php;toolbar:false;">li < a.active {
property: value;
}</pre>
<p>Obviously, it is possible to achieve this using JavaScript, but I was hoping for a workaround that was native to CSS Level 2. </p>
<p>The menu I'm trying to style is generated by a CMS, so I can't move the active element into the <code><li></code> element... (unless I theme the menu creation module, but I'd rather not do that). </p>
You can use
:has()
CSS pseudo-classBut it has limited browser support (Firefox is not supported yet).
Currently there is no way in CSS to select an element's parent element so that it works correctly in all browsers.
Selectors Level 4 Working Draft contains a
:has()
pseudo-class that will provide this functionality. It would be similar to jQuery's implementation, but is currently not supported by Firefox.Currently only Firefox does not support this feature by default.
Meanwhile, if you need to select a parent element with full cross-browser support, you will have to use JavaScript in Firefox.