How can I use the nth-of-type css selector on <span> elements that are contained within the <li> elements of a <ul>?
I would have expected span:nth-of-type(odd) and span:nth-of-type(even) to work but they did not.
span:nth-of-type(even) {
background-color: grey;
}
span:nth-of-type(odd) {
background-color: blue;
}
<ul>
<li>
<span>Test 1</span>
</li>
<li>
<span> 2 Test</span>
</li>
</ul>
<br>
Should look like this:
<br>
<span>Test 1</span>
<br>
<span> 2 Test</span>
You have to do it like this:
The selector
nth-of-type(and alsofirst-child,last-childornth-child) refer to their parents. In this case the parent is the<li>-tag. So both<span>s are odd elements as both are the first-child element. And both get selected the way you defined the CSS-rule. The CSS-rule here selects their parents as they can be alternating and sets the style for the children accordingly.