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>
?
When you group CSS selectors, you apply the same styles to several different elements without repeating the styles in your stylesheet. Instead of having two, three, or more CSS rules that do the same thing (set the color of something to red, for example), you use a single CSS rule that accomplishes the same thing.
The CSS child combinator ( > ) can be used to select all elements that are the immediate children of a specified element. A combinator combines and explains the relationship between two or more selectors.
The '>' Symbol CSS rules will be applied to elements which are direct children of the particular element. It will target (represented with a green dot in HTML image) all the <p> tags which are immediate children of container <div>, but the children of children will not be selected (represented with the red dot).
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:
color
propertyinherit
valueIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With