如何在ul标签中使用nth-of-type? [英] How to style using nth-of-type within a ul tag?
问题描述
如何在< span>
上使用 nth-of-type
css selector在< ul>
?
$ b的
< li>
$ b 我会期望 span:nth-of-type(odd)
和 span:nth-of-type(even) / code>工作,但他们没有。
有问题的页面如下:
< style>
span:nth-of-type(even){
background-color:gray;
}
span:nth-of-type(odd){
background-color:blue;
}
< / style>
< ul>
< li>
< span>测试1< / span>
< / li>
< li>
< span> 2测试< / span>
< / li>
< / ul>
< br>
应该看起来像这样:
< br>
< span>测试1< / span>
< br>
< span> 2测试< / span>
这里是 JSFiddle 显示正在执行的问题。
<你必须这样做:
li:第n类型(奇数) span {}
li:nth-of-type(even)> span {}
选择器 nth-of-type
(以及 first-child
, last-child
或 nth- code>)指的是他们的父母。在这种情况下,父代是
< li>
-tag。因此,< span>
都是奇数元素,因为两者都是 first-child元素。两者都选择了你定义CSS规则的方式。 CSS规则在这里选择他们的父母,因为他们可以交替,并相应地设置孩子的风格。
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.
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.
这篇关于如何在ul标签中使用nth-of-type?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!