有了nth-child选择器,选择指定的li时候,就不用写额外的类名,如下:
ul li {
width: 20px;
height: 20px;
background-color: red;
margin-bottom: 10px;
list-style: none;
}
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
- 我要让除了第一个li的其他所有li都变成绿色:
方法一:
ul li:nth-child(n+2) {
background-color: green;
}
/* n从0开始,表示从第二个开始 */
方法二:
ul li:not(:first-child) {
background-color: green;
}
/* 取反 */
页面上:
2. 我要让最后两个li都变成绿色:
ul li:nth-child(n+3) {
background-color: green;
}
/* n从0开始,表示从第三个开始 */
页面上效果:
3. 我想让除了最后一个li的其他所有li变成绿色
方法一:
ul li:nth-last-child(n+2) {
background-color: green;
}
/* n从0开始,这里有一个nth-last-child,表示从最后一个开始,
n+2表示从倒数二个开始 */
方法二:
.sel div:not(:last-child) {
background-color: green;
}
页面效果:
4.我要所有2二点倍数的li变为绿色:
方法一:
ul li:nth-child(2n) {
background-color: green;
}
/* 同理3的倍数时3n, 5的倍数时5n */
方法二:
ul li:nth-child(even) {
background-color: green;
}
页面效果:
5.所有偶数行蓝色,所有奇数行黄色
ul li:nth-child(even) {
background-color: #87ceeb;
}
ul li:nth-child(odd) {
background-color: #ffff00;
}
页面效果: