search

Home  >  Q&A  >  body text

Does parent selector exist 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 { 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>
P粉713866425P粉713866425465 days ago514

reply all(2)I'll reply

  • P粉141911244

    P粉1419112442023-08-22 00:53:02

    You can use :has() CSS pseudo-class

    But it has limited browser support (Firefox is not supported yet).

    reply
    0
  • P粉536532781

    P粉5365327812023-08-22 00:27:06

    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.

    li:has(> a.active) { /* 应用于li标签的样式 */ }
    

    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.

    reply
    0
  • Cancelreply