skip to Main Content

I have the following code:

<ul class="m">
        <li>test</li>
        <li>l1
            <ul>
                <li>l11</li>
                <li>l12</li>
            </ul>
        </li>
        <li>l2</li>
    </ul>

I want to select only the li which are direct child of ul with the m class. I added the following css rule:

ul.m> li{
            color: orange;
        }

But unfortunately all the li are in orange even those which are not direct child of ul with class m. I don’t know why?


ul.m>li {
  color: orange;
}
<ul class="m">
  <li>test</li>
  <li>l1
    <ul>
      <li>l11</li>
      <li>l12</li>
    </ul>
  </li>
  <li>l2</li>
</ul>

2

Answers


  1. Your selector only applies to the elements you are expecting, however the child li inherit the style from their parents by default. This can be avoided by explicitly setting a "default" value for those elements, e.g.

    li {
      color: #000;
    }
    
    ul.m > li {
      color: orange;
    }
    <ul class="m">
      <li>test</li>
      <li>l1
        <ul>
          <li>l11</li>
          <li>l12</li>
        </ul>
      </li>
      <li>l2</li>
    </ul>
    Login or Signup to reply.
  2. Technically this because of the way color inherits its value (i.e. if a style is set on a higher-up element ).
    See color – Formal Definition.

    Because no value has been set, the color will inherit whatever color it can find (in this case, from its parent)

    You could set the colour to the initial value:

    li {
      color: initial;
    }
    ul.m>li {
      color: orange;
    }
    <ul class="m">
      <li>test</li>
      <li>l1
        <ul>
          <li>l11</li>
          <li>l12</li>
        </ul>
      </li>
      <li>l2</li>
    </ul>

    Note: This could lead to unexpected side-effects because of browser-implementation – see this answer.
    Ultimately this is why developers often include a Reset StyleSheet too

    Alternatively, you could specify the color yourself:

    li {
      color: black;
    }
    ul.m>li {
      color: orange;
    }
    <ul class="m">
      <li>test</li>
      <li>l1
        <ul>
          <li>l11</li>
          <li>l12</li>
        </ul>
      </li>
      <li>l2</li>
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search