search

Home  >  Q&A  >  body text

Is there a parent selector in CSS?

<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粉270842688P粉270842688538 days ago533

reply all(2)I'll reply

  • P粉404539732

    P粉4045397322023-08-22 09:40:21

    You can use :has() CSS pseudo-class

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

    reply
    0
  • P粉794851975

    P粉7948519752023-08-22 00:17:37

    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.

    reply
    0
  • Cancelreply