Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CSS selector $parent > $child selects all <li> child elements in nested lists

The css selector $parent > $immediateChild is not working for nested lists.
Only the direct <li> of the level-1 list should be red, but the selector selects all <li> in all nested lists.

ul.level-1 > li
{
    color: red;
}
<ul class="level-1">
    <li>Level 1
      <ul>
          <li>Level 2</li>
      </ul>
    </li>
</ul>

Also found this post and it states that the second <ul> needs to be in the <li> of the first to have valid html. I did that but it’s not working.

/EDIT: I just transformed my nested list to <div>s instead like before. It’s a menu with a submenu and sub-submenu. The nested list is hard to address via CSS and there were also issues with my flexbox submenu.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So, I can’t recommend doing menus with a (nested) list because all styles are natively inherited to all childs which is probably not what you want. The accepted answer would solve this particular problem, though.

>Solution :

Styles automatically get applied ("inherited") to descendants of targeted children, just like in your example.

If you want the second layer of li elements to e.g. have black text color, you have to target them again:

ul.level-1 > li
{
    color: red;
}
ul.level-1 > li > ul > li
{
    color: black;
}
<ul class="level-1">
    <li>Level 1 - 1 child
      <ul>
          <li>Level 2</li>
      </ul>
    </li>
    <li>Level 1 - no children</li>
    <li>Level 1 - 1+ children
      <ul>
          <li>Level 2</li>
          <li>Level 2</li>
      </ul>
    </li>
</ul>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading