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
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.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: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: