序号选择器
1、例子
举例 | 意义 | 兼容 |
---|
:first-child | 第一个子元素 | 兼容IE7 |
:last-child | 最后一个子元素 | 兼容IE9 |
:nth-child(3) | 第3个子元素 | 兼容IE9 |
:nth-of-type(3) | 第3个某类型子元素 | 兼容IE9 |
:nth-last-child(3) | 倒数第3个元素 | 兼容IE9 |
:nth-last-of-type(3) | 倒数第3个某类型子元素 | 兼容IE9 |
2、:first-child
:first-child表示“选择第一个子元素”,比如下面的例子就表示选择.box1盒子中第一个p
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1 p:first-child{
//不要忘记p;
color:red;
}
</style>
</head>
<body>
<div class="box1">
<p>1</p>
//被选择
<p>11</p>
<p>111</p>
<p>1111</p>
</div>
</body>
</html>
3、:nth-child
* :nth-child()可以写成an+b的形式,表示从b开始每a个选一个,注意不能写成b+an
* 可以选择任意序号的子元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box2 p:nth-child(3n+2){
color:red;
}
</style>
</head>
<body>
<div class="box2">
<p>1</p>
<p>11</p>
<p>111</p>
<p>1111</p>
<p>11111</p>
<p>1111111</p>
<p>1</p>
<p>111</p>
<p>111</p>
<p>111</p>
<p>1111</p>
</div>
</div>
</body>
</html>
2、2n+1等价于odd,表示奇数;
3、2n等价于even,等价于偶数;
4、:nth-of-type()
:nth-of-type()将选择同种标签指定序号的子元素;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box4 p:nth-of-type(3){
color:red;
}
</style>
</head>
<body>
<div class="box4">
<p>1</p>
<p>11</p>
<h3>99</h3>
<h3>999</h3>
<p>111</p>//yes
<p>1111</p>
</div>
</body>
</html>