skip to Main Content

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.

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.

2

Answers


  1. 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>
    Login or Signup to reply.
  2. A lot of styles are inherited down to the child elements of the element you style.

    If the default value of an CSS property is inherit, it uses the value the parent has set for that property.

    Styling the second ul would already be enough to change the color.

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

    Another way to fix the problem is to reset the color:

    color: initial;
    

    This would also make the text color revert to the original (black in most of the cases).

    This answer on StackOverflow has a list of inherited properties.

    web.dev also has some information about it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search