Reputation: 54419
Could someone explain to me why CSS > sign (direct child) overrides the default color of all <li>
tags in this example:
ul > li {
color:red;
}
<ul>
<li>This should be red
<ol>
<li>default color 1</li>
<li>default color 2</li>
</ol>
</li>
<li>And this should be red also
<ol>
<li>default color 3</li>
<li>default color 4</li>
</ol>
</li>
</ul>
I know that I can fix it by adding li { color: black; }
, but I'm wondering why ul > li
overrides the default color for <li>
?
Upvotes: 34
Views: 1460
Reputation: 371879
The issue is not the child combinator (>
), it's the color
property, which is inheritable.
Although the initial value of the color
property varies from browser to browser, inherit
is common. This means that an element's text color is inherited from the parent. You're seeing this in your code.
In contrast, the border
property is not inheritable. Note how, unlike the text color, it applies only to your targeted li
:
ul > li {
color: red;
border: 1px solid black;
}
li { border: 1px solid inherit !important; }
<ul>
<li>This should be red
<ol>
<li>default color 1</li>
<li>default color 2</li>
</ol>
</li>
<li>And this should be red also
<ol>
<li>default color 3</li>
<li>default color 4</li>
</ol>
</li>
</ul>
To achieve your styling objective, set a default color for the li
element. This will override inherit
. Here's an example:
ul > li {
color: red;
}
li {
color: black;
}
<ul>
<li>This should be red
<ol>
<li>default color 1</li>
<li>default color 2</li>
</ol>
</li>
<li>And this should be red also
<ol>
<li>default color 3</li>
<li>default color 4</li>
</ol>
</li>
</ul>
References:
Upvotes: 48
Reputation: 6780
The ol
is inheriting the styles. You will need to specify styles for the inner list.
Upvotes: 4
Reputation: 944146
The default value for the color
property, for most elements, is inherit
, not black
. This means it takes whatever value the parent (ol
) element has. (And that's after the ol
inherits from the red li
).
You would have to set an explicit colour to override it. For example:
ul > li li {
color: black;
}
or
ol > li {
color: black;
}
Upvotes: 17