I'm testing a little code to learn about selectors in CSS. This is my code:
/* Direct Child Selector */
ul > li {
color: gray;
}
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3
<ol>
<li>List Item 3.1</li>
<li>List Item 3.2</li>
<li>List Item 3.2</li>
</ol>
</li>
<li>List Item 4</li>
</ul>
The result is not as expected.
I have coded this and what I'd expect is that just the List Items 1,2,3 and 4 change the color, but I don't understand why also the sub-items have changed the color. Thanks in advance for any help.
Because that's how CSS works. Elements inside of a styled element will inherit those style rules. The style rule shown targets the <li>
elements immediately within the <ul>
element, and this entire structure is "an <li>
element":
<li>List Item 3
<ol>
<li>List Item 3.1</li>
<li>List Item 3.2</li>
<li>List Item 3.2</li>
</ol>
</li>
You can separately target the <ol>
element and apply a style rule there, which would take precedence over the inherited rule:
/* Direct Child Selector */
ul > li {
color: gray;
}
ol {
color: black;
}
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3
<ol>
<li>List Item 3.1</li>
<li>List Item 3.2</li>
<li>List Item 3.2</li>
</ol>
</li>
<li>List Item 4</li>
</ul>
As an aside, open your browser's debugging tools and take a look at the DOM inspector. When selecting an element in the DOM, you can observe the variety of style rules being applied. User agent defaults, inherited rules, specifically targeted rules, etc. When multiple style rules are applied, this will show you which ones have a higher precedence for any given element.