首先,nth-child
是选择父元素里面的第几个子元素,不管是第几个类型,而 nt-of-type
是选择指定类型的元素。
举例说明:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div :nth-child(1) {
background-color: pink;
}
div :nth-child(2) {
background-color: purple;
}
/* 这个选不到 因为 nth-child 是选择父元素里面的第几个子元素,不管是第几个类型*/
div span:nth-child(1) {
background-color: pink;
}
/* 此时选取的是div中的第二个子元素,即是对第一个 span 标签操作 */
div span:nth-child(2) {
background-color: pink;
}
/* 总结: :nth-child(n) 选择 父元素里面的第 n个孩子, 它不管里面的孩子是否同一种类型 */
/* of-type 选择指定类型的元素 以下三行代码是对div中的 span 进行操作*/
div span:first-of-type {
background-color: purple;
}
div span:last-of-type {
background-color: skyblue;
}
div span:nth-of-type(2) {
background-color: red;
}
</style>
</head>
<body>
<div>
<p>我是一个段落</p>
<span>我是span1</span>
<span>我是span2</span>
<span>我是span3</span>
</div>
<!-- ul 里面我们只允许放li 所以 nth-child 和 nth-of-type 就一样了 -->
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</body>
</html>
注:E:nth-child(n) 与 E:nth-of-type(n) 中的n是从0开始的,且第 0 个元素或者超出了元素的个数会被忽略,如 -n+5 表示前五个元素。