6、选择器first-child、last-child、nth-child和nth-last-child
1)first-child
单独指第一个子元素的样式
2)last-child
单独指最后一个子元素的样式
3)nth-child
nth-child(n)匹配正数下来第N个子元素
nth-child (odd) 匹配正数下来第奇数个子元素
nth-child (even) 匹配正数下来第偶数个子元素
<style>
li:first-child{
background: #ff6600;
}
li:last-child{
background: green;
}
li:nth-child(odd){
background: red; /*奇数*/
}
li:nth-child(even){
background: #ff6600; /*偶数*/
}
</style>
<body>
<ul>
<li>第一个项目</li>
<li>第二个项目</li>
<li>第三个项目</li>
<li>第一个项目</li>
<li>第一个项目</li>
<li>第一个项目</li>
<li>第一个项目</li>
<li>第一个项目</li>
</ul>
</body>
部分结果:
4)nth-last-child
nth-last-child(n)匹配倒数下来第N个子元素
nth-last-child (odd) 匹配倒数下来第奇数个子元素
nth-last-child (even) 匹配倒数下来第偶数个子元素
7、选择器nth-of-type和nth-last-type
1)、在使用nth-child和nth-last-child产生的问题
<h2>标题</h2>
<p>内容</p>
<h2>标题</h2>
<p>内容</p>
<h2>标题</h2>
<p>内容</p>
<h2>标题</h2>
<p>内容</p>
如果使用nth-child(odd),显示结果是所有的h2行都会变掉,但是我们想实现的是第一行和第三行h2改变,问题在于nth-child把p行加入进去了
2)、使用nth-of-type和nth-last-of-type
nth-of-type:正数
nth-last-of-type:倒数
使用nth-of-type,就能实现同一元素的改变。
8、循环使用样式
nth-child(An+B),A表示每次循环中包括几种样式,B表示指定的样式在循环中所处的位置
<style>
li:nth-child(4n+1){
background: #000000;
}
li:nth-child(4n+2){
background: #ffffff;
}
li:nth-child(4n+3){
background: #ff1b00;
}
li:nth-child(4n+4){
background: green;
}
</style>
<body>
<li>第一个项目</li>
<li>第一个项目</li>
<li>第一个项目</li>
<li>第一个项目</li>
<li>第一个项目</li>
<li>第一个项目</li>
<li>第一个项目</li>
<li>第一个项目</li>
</body>
显示结果: