Is there a parent selector in CSS?
P粉270842688
2023-08-21 10:49:24
<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 {
Attribute: value;
}</pre>
<p>Obviously, it is possible to achieve this using JavaScript, but I was hoping for a CSS Level 2 native workaround. </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 don't want to do that). </p>
You can use
:has()
CSS pseudo-classBut its browser support is limited (currently not supported by Firefox).
Currently there is no way in CSS to select the parent of an element in all browsers.
Selectors Level 4 Working DraftIncludes a
:has()
pseudo-class that will provide this capability. It would be similar to jQuery's implementation, but is currently not supported by Firefox.Firefox is the only major browser that currently does not support it by default.
In the meantime, if you need to select a parent element with full cross-browser support, you will have to use JavaScript in Firefox.