结论
1. nth-child选取时, 会给所有子元素标记序号, 然后通过序号选中想要元素
2. nth-of-type选取时, 会按照指定类型给子元素标记序号, 然后通过序号选中想要元素
1. nth-child选中元素
代码:
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>CSS结构伪类选择器(复合选择器中nth-child和nth-of-type的区别)</title>
<style>
body div:nth-child(1) {
width: 200px;
height: 200px;
background-color: skyblue;
}
body div:nth-child(3) {
width: 200px;
height: 200px;
background-color: skyblue;
}
</style>
</head>
<body>
<div></div>
<p>我是P标签</p>
<div></div>
</body>
</html>
运行:
解释:
通过案例可以看出来, nth-child在选取元素的时候,相当于给基本选择器(body)下的所有元素都设置了序号, 然后通过序号和元素类型来选中元素。如果指定的信息和标记的信息不能正确匹配,那么就不会选中,比如案例中写body div:nth-child(2), 就会无效, 因为标记序号为2的元素不是<div>而是<p>
2. nth-of-type选中元素
代码:
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>CSS结构伪类选择器(复合选择器中nth-child和nth-of-type的区别)</title>
<style>
body div:nth-of-type(1) {
width: 200px;
height: 200px;
background-color: skyblue;
}
body div:nth-of-type(2) {
width: 200px;
height: 200px;
background-color: skyblue;
}
</style>
</head>
<body>
<div></div>
<p>我是P标签</p>
<div></div>
</body>
</html>
运行:
解释:
nth-of-type在选取元素的时候,只给基本选择器(body)下指定类型的元素设置了序号, 然后通过序号和元素类型来选中元素。案例中<p>元素就不会被标记序号 , 因为 div:nth-of-type指定了, 只给div类型的元素标记序号。