I was finishing up selectors and testing my knowledge and encountered a problem that makes no sense.
In theory, the code below should color all first children that
This is because you have nested li
s.
The second inner li
is being coloured red because it's inheriting that rule from the style applied to the first child outer li
, ie its parent.
li:first-child { color: red; }
li:not(:first-child) { color: black; }
That will override the inheritance and result in the text of the first outer and inner li
s being red. Fiddle
Alternatively, if you want to colour only the inner li
s:
li li:first-child { color: red; }
It happens because the color is inherited from the parent element, try to add this to your CSS to override it:
li {
color:initial;
}
color
is inherited from the parent element....in this case the li:first-child
So when you tell the li
to be a red color this is inherited by all its children.
You have no rule to override this for the children so they are colored by inheritance/
The li:first-child selector will also select the first li element in your parent list. You can target your selector using direct descendents or you can use classes.
This is the preferred option as it will automatically namespace your css. All your selectors will start with .menu when targeting child elements.
<ul class="menu">
<li>Peter<ol>
<li>Juan</li>
<li>Samuel</li>
</ol></li>
</ul>
.menu ol li:first-child{
color: red;
}
If you want to override the style of a menu, you can use an extra class on the menu element and for example target it with the following selector.
.menu.horizontal
This option has the same benefits of the first option, but now .menuItem is namespaced on its own.
<ul>
<li class="menuItem">Peter<ol>
<li>Juan</li>
<li>Samuel</li>
</ol></li>
</ul>
.menuItem ol li:first-child{
color: red;
}
ol>li:first-child{
color: red;
}
It is always better to use classes because if you use ol elements in other places, the selector would still apply there.