NotaGuruAtAll NotaGuruAtAll - 3 months ago 17
CSS Question

Nested Hierarchy CSS Issue

Here is the fiddle:

https://jsfiddle.net/3h1hxy2w/4/

I'm trying to make a reusable set of CSS rules so that items under .ancestor class the first < l i>'s in .children groups would be visible, but their children would remain hidden. The problem is it seems to travel down opening all 'children' groups.

First I close all of the children with display: none, then open any descendants of .ancestor

In this situation, I cannot add any helpful classes or use jQuery. The current output is like this:

Item One

more items
STUFF!
more stuff
even more stuff
more items
More items
more items 2
more items
more items
More items
more items
more items
more items
More items

Item Two

Item Three


but I'm shooting for

Item One
more items
STUFF!
more stuff
even more stuff
more items
More items
more items 2
more items

Item Two

Item Three


Any ideas?

This is the html

<ul id="hier">
<li class="ancestor">
Item One
<ul class="children">
<li class="ancestor">more items
<ul class="children">
<li class="ancestor current-parent">
Parent
<ul class="children">
<li class="current-cat">STUFF!</li>
<li>more stuff</li>
<li>even more stuff</li>
</ul>
</li>
<li>more items</li>
<li>More items</li>
</ul>
</li>
<li>more items 2
<ul class="children">
<li>more items</li>
<li>more items</li>
<li>More items</li>
</ul>
</li>
<li>more items
<ul class="children">
<li>more items</li>
<li>more items</li>
<li>More items</li>
</ul>
</li>
</ul>
</li>
<li>
Item Two
<ul class="children">
<li>more items
<ul class="children">
<li>more items</li>
<li>more items</li>
<li>More items</li>
</ul>
</li>
<li>more items
<ul class="children">
<li>more items</li>
<li>more items</li>
<li>More items</li>
</ul>
</li>
<li>more items
<ul class="children">
<li>more items</li>
<li>more items</li>
<li>More items</li>
</ul>
</li>
</ul>
</li>
<li>
Item Three
<ul class="children">
<li>more items
<ul class="children">
<li>more items</li>
<li>more items</li>
<li>More items</li>
</ul>
</li>
<li>more items
<ul class="children">
<li>more items</li>
<li>more items</li>
<li>More items</li>
</ul>
</li>
<li>more items
<ul class="children">
<li>more items</li>
<li>more items</li>
<li>More items</li>
</ul>
</li>
</ul>
</li>
</ul>


And here is the CSS so far

ul { list-style-type: none; }

#hier li .children li { display: none; }

.ancestor .children li { display: block !important;}

Answer
ul { list-style-type: none; }
.children li { display: none; }
.ancestor > .children > li { display: block; }

It is always important to avoid !important. In this instance, the direct descendant selector (>) is your friend. If you require the id component of the rule, just be sure to apply it to both rules.

Comments