How to style using nth-of-type within a ul tag?

2019-06-10 03:54发布

问题:

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.

The page in question is below:

<style>
  span:nth-of-type(even) {
    background-color: grey;
  }

  span:nth-of-type(odd) {
    background-color: blue;
  }
</style>
<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>

Here is a JSFiddle to show the issue in action.

回答1:

You have to do it like this:

li:nth-of-type(odd) > span {}
li:nth-of-type(even) > span {}

The selector nth-of-type (and also first-child, last-child or nth-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.



回答2:

The nth elements you're looking to count are the <li> elements, not the <span> elements. There's no reason to use nth-of-type over nth-child, because <ul> elements can only contain <li> elements as children:

li:nth-child(even) > span {
    background-color: gray;
}
li:nth-child(odd) > span {
    background-color: blue;
}