转载:https://blog.csdn.net/longgeaisisi/article/details/78154169
nth-child(n)、first-child、last-child用法
注:nth-child(n)选择器匹配父元素中的第n个子元素。
n可以是一个数字,一个关键字,或者一个公式。
1.nth-child(n)用法:
1.1 nth-child(3)
表示选择列表中的第3个标签,代码如下:
li:nth-child(3){background:#fff}
1.2 nth-child(2n)
表示选择列表中的偶数标签,即选择 第2、第4、第6…… 标签,代码如下:
li:nth-child(2n){background:#fff}
1.3 nth-child(2n-1)
表示选择列表中的奇数标签,即选择 第1、第3、第5、第7……标签,代码如下:
li:nth-child(2n-1){background:#fff}
1.4 nth-child(n+3)
表示选择列表中的标签从第3个开始到最后,代码如下:
li:nth-child(n+3){background:#fff}
1.5 nth-child(-n+3)
表示选择列表中的标签从0到3,即小于3的标签,代码如下:
li:nth-child(-n+3){background:#fff}
1.6 nth-last-child(3)
表示选择列表中的倒数第3个标签,代码如下:
li:nth-last-child(3){background:#fff}
2.first-child用法:
2.1 first-child
first-child表示选择列表中的第一个标签。代码如下:
li:first-child{background:#fff}
3. last-child用法:
3.1 last-child
last-child表示选择列表中的最后一个标签,代码如下:
li:last-child{background:#fff}
3.2 nth-last-child()用法
括号里写倒数第几个
li:nth-last-child(2){background:#ff0000;}
4.使用场景
4.1html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{margin: 0;padding: 0;}
.clearfix:before, .clearfix:after {
content: '.';
display: block;
visibility: hidden;
font-size: 0;
line-height: 0;
width: 0;
height: 0;
}
.clearfix:after {
clear: both;
}
.clearfix {
zoom: 1;
}
li{
list-style: none;
}
.list{
width: 430px;
border: 1px solid blue;
padding: 10px 10px 0;
margin: 0 auto;
}
.list li{
float: left;
width:100px;
height: 50px;
background-color: rgba(0,0,0,0.5);
margin-right: 10px;
margin-bottom: 10px;
}
.list li:nth-child(4){
margin-right: 0;
}
.list li:nth-child(8){
margin-right: 0;
}
</style>
</head>
<body>
<ul class="list clearfix">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
</html>
4.2效果