Is there a CSS parent selector?

How do I select the <li> element that is a direct parent of the anchor element?

In example my CSS would be something like this:

li < a.active {
    property: value;
}

Obviously there are ways of doing this with JavaScript but I'm hoping that there is some sort of workaround that exists native to CSS Level 2.

The menu that I am trying to style is being spewed out by a CMS so I can't move the active element to the <li> element... (unless I theme the menu creation module which I'd rather not do).

Any ideas?


There is currently no way to select the parent of an element in CSS.

If there was a way to do it, it would be in either of the current CSS selectors specs:

  • Selectors Level 3 Spec
  • CSS 2.1 Selectors Spec
  • In the meantime, you'll have to resort to JavaScript if you need to select a parent element.


    The Selectors Level 4 Working Draft includes a :has() pseudo-class that works the same as the jQuery implementation. As of May 2018, this is still not supported by any browser .

    Using :has() the original question could be solved with this:

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

    I don't think you can select the parent in css only.

    But as you already seem to have an .active class, wouldn't it be easier to move that class to the li (instead of the a )? That way you can access both the li and the a via css only.


    You can use this script.

    *! > input[type=text] { background: #000; }
    

    This will select any parent of a text input. But wait, there's still much more. If you want, you can select a specified parent:

    .input-wrap! > input[type=text] { background: #000; }
    

    or select it when it's active:

    .input-wrap! > input[type=text]:focus { background: #000; }
    

    Check out this HTML:

    <div class="input-wrap">
        <input type="text" class="Name"/>
        <span class="help hide">Your name sir</span>
    </div>
    

    you can select that span.help when the input is active and show it:

    .input-wrap! .help > input[type=text]:focus { display: block; }
    

    There are many more capabilities; just check out the documentation of the plugin.

    BTW, it works in IE.

    链接地址: http://www.djcxy.com/p/524.html

    上一篇: 声明式编程和命令式编程有什么区别?

    下一篇: 有没有一个CSS父母选择器?