1.X:first-child
匹配子集的第一个元素,IE7就可以支持。
li:first-child{
background: red;
}
2.X:last-child
与firs-child刚好相反,匹配子集的最后一个元素,IE8不支持
li:last-child{
background: blue;
}
3.X:nth-child(n)
匹配子集的第n个元素,n从1开始
li:nth-child(5){
background: #843534;
}
4.X:nth-last-child(n)
匹配子集的倒数第n个元素
li:nth-last-child(3){
background: #ffff00;
}
5.X:nth_child(odd)
匹配子集的奇数元素,1,3,5,7...个元素
li:nth-child(odd){
background: #0066dd;
}
6.X:nth-child(even)
匹配子集的偶数元素,2,4,6,8...个元素
li:nth-child(even){
background: #ee66cc;
}
7.X:only-child
这个伪类一般用的比较少,比如上述代码匹配的是div下的有且仅有一个的p,也就是说,如果div内有多个p,将不匹配。
示例:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
ul{
background-color: #aaaaaa;
height: 100px;
}
li{
list-style:none;
border-radius: 50px;
background-color: coral;
height: 100px;
width: 100px;
float: left;
line-height: 100px;
font-size: 50px;
text-align: center;
margin-left: 5px;
display: block;
}
/*奇数*/
li:nth-child(odd){
background:#4cae4c;
}
/*偶数*/
li:nth-child(even){
background: #ee66cc;
}
li:first-child{
background: red;
}
li:last-child{
background: blue;
}
li:nth-child(5){
background: #843534;
}
li:nth-last-child(3){
background: #ffff00;
}
</style>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
</body>
</html>