Search code examples
csscss-selectors

Select parent n layers up in the tree using CSS?


I have an app with relatively complex DOM structure with 20+ layers of divs.

If I have a div with class="active" somewhere in the middle of the tree, how can I select it's parent n layers up in the tree using CSS?

For example, how do I select the div marked in uppercase (4 layers up) in the following tree ? :

<DIV>
  <div>
    <div>
      <div>
        <div class="active">
        </div>
      </div>
      <div>
      </div>
    </div>
  </div>
</DIV>

Same considering first-child ? How to select a first-child n layers down the tree ?


Solution

  • Based on this article I found titling CSS4 Preview, it will be possible in CSS4 to style parent elements. The article shows that it would be possible to style parent elements like the following:

    $div > div > div > div.active { border: 1px solid #ccc; }
    

    (Given example would style the div nested 3 layers up in the tree related to div.active)

    Going back to my app, using PHP and inline CSS, I would be able to control the n (nesting depth).

    Until CSS4 though, I will use some kind of jQuery solution.