话不多说,代码刚起来。
<nav >
<ul>
<li>item01</li>
<li>item02</li>
<li>item03</li>
<li>item04</li>
<li>item05</li>
</ul>
<div>
<span>你好</span>
</div>
</nav>
ul:last-child ,ul:first-child
选中第一个/最后一个ul,child并不代表子元素,而是同级元素。ul:first-child{ border: 3px double red; }
- 匹配所有兄弟节点中位置位于an+b位置的元素;其中a,b可以随意取值,n依次增加得到值。例如a=1,b=1;n=1时选中1*1+1=2位元素。通常由2n+1,2n分别选中奇数、偶数位置的元素。nth-child(odd) | nth-child(even) 也可以用来表示奇数偶数元素
li:nth-child(2n+1){
color: red;
}
li:nth-child(2n){
color: blue;
}
将a设置位0,即可选中单个元素,例如 选中第三个li,设置字体颜色位绿色
li:nth-child(3){
color: seagreen;
}
将a设置成1,nth-child(nn++b) , n从0依次增加,即选中从b开始的后面所有元素。
li:nth-child(n+3){
color: seagreen;
}
3. 如果我们在item03前加一个section标签 ,依旧对第三个元素添加字体颜色
<nav >
<ul>
<li>item01</li>
<li>item02</li>
<section>section2</section>
<li>item03</li>
<li>item04</li>
<li>item05</li>
</ul>
<div>
<span>你好</span>
</div>
</nav>
但是第三个li并没有效果。但是如果我们使用li:nth-of-type(3){ color: seagreen; }
就可以实现
nth-of-type()用法和nth-child()用法类似,但是 nth-of-type()可以追踪找到这个类型的第几个元素,但是nth-child()一旦没有找到该元素(比如上例这种中间插入其他元素)就会放弃给与的样式。
Tips
- nth-child 按照位置来寻找元素添加样式,如果该元素位置前加了其他元素就会失效。nth-of-type是根据类型一直追踪该元素,不会中途放弃。
- nth系列只能被标签类调用,无法被类名调用
- nth系列ie9,safari3以上都可以兼容,兼容性很好。
自己之前一直都很乱,很感谢原博主的讲解,以下是参考的原文链接地址
https://www.cnblogs.com/Wayou/p/css3-nth-selector.html