Is there a parent selector in CSS?
P粉270842688
P粉270842688 2023-08-21 10:49:24
0
2
467
<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>
P粉270842688
P粉270842688

reply all(2)
P粉404539732

You can use :has() CSS pseudo-class

But its browser support is limited (currently not supported by Firefox).

P粉794851975

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.

li:has(> a.active) { /* styles to apply to the li tag */ }

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template