Complex CSS selector for parent of active child

Deeksy picture Deeksy · Sep 5, 2008 · Viewed 317.1k times · Source

Is there a way to select a parent element based on the class of a child element in the class? The example that is relevant to me relating to HTML output by a nice menu plugin for http://drupal.org. The output renders like this:

<ul class="menu">  
    <li>  
        <a class="active">Active Page</a>  
    </li>  
    <li>    
        <a>Some Other Page</a>  
    </li>  
</ul>  

My question is whether or not it is possible to apply a style to the list item that contains the anchor with the active class on it. Obviously, I'd prefer that the list item be marked as active, but I don't have control of the code that gets produced. I could perform this sort of thing using javascript (JQuery springs to mind), but I was wondering if there is a way to do this using CSS selectors.

Just to be clear, I want to apply a style to the list item, not the anchor.

Answer

Sam Hasler picture Sam Hasler · Sep 5, 2008

According to Wikipedia:

Selectors are unable to ascend

CSS offers no way to select a parent or ancestor of element that satisfies certain criteria. A more advanced selector scheme (such as XPath) would enable more sophisticated stylesheets. However, the major reasons for the CSS Working Group rejecting proposals for parent selectors are related to browser performance and incremental rendering issues.

And for anyone searching SO in future, this might also be referred to as an ancestor selector.

Update:

The Selectors Level 4 Spec allows you to select which part of the select is the subject:

The subject of the selector can be explicitly identified by prepending a dollar sign ($) to one of the compound selectors in a selector. Although the element structure that the selector represents is the same with or without the dollar sign, indicating the subject in this way can change which compound selector represents the subject in that structure.

Example 1:

For example, the following selector represents a list item LI unique child of an ordered list OL:

OL > LI:only-child

However the following one represents an ordered list OL having a unique child, that child being a LI:

$OL > LI:only-child

The structures represented by these two selectors are the same, but the subjects of the selectors are not.

Although this isn't available (currently, November 2011) in any browser or as a selector in jQuery.