nth-child
以当前所有兄弟节点的数量来计数,然后根据nth-child前面的标签来对相应的标签进行渲染。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div:nth-child(2n+1) {
color: orange
}
li:nth-child(2n+1) {
color: red;
}
</style>
</head>
<body>
<ul>
<li>123</li>
<li>123</li>
<li>123</li>
<div>123</div>
<div>123</div>
<div>123</div>
<li>123</li>
</ul>
</body>
</html>
結果:
nth-of-type
.item:nth-of-type():如果是class,以兄弟节点中所有item类的数量计算,再以不同类型的节点为一组,按各自的数量进行计算:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
li {
counter-increment: num -3;
}
li::after {
content: counter(num)
}
.div:nth-of-type(3) {
color: red;
}
</style>
</head>
<body>
<ul>
<li class="div"></li>
<li class="div"></li>
<li class="div"></li>
<div class="div">123</div>
<div class="div">123</div>
<div class="div">123</div>
<li class="div"></li>
</ul>
</body>
</html>
结果:
div:nth-of-type,如果是元素开头,所有对应的元素的数量进行计算
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
li {
counter-increment: num -3;
}
li::after {
content: counter(num)
}
li:nth-of-type(3) {
color: red;
}
div:nth-of-type(3){
color:blue
}
</style>
</head>
<body>
<ul>
<li></li>
<li></li>
<li></li>
<div>123</div>
<div>123</div>
<div>123</div>
<li></li>
</ul>
</body>
</html>
结果:
因此可以总结:对于nth-of-type,会根nth-of-type前面的来进行选择,如果是class,会先选出所有相同的class,然后根据标签的不同分类,如果前面是标签,那么直接选中相同类型的标签。