nth-child与nth-of-type区别

示例详细理解:nth-child(n)与:nth-of-type(n)区别

childselector:nth-child(index)
1,子选择器(childselector,这里是p选择器)选中元素的父级元素ul,
得到所有子元素(包括自己和所有兄弟元素)(l1,p1,p2,l2,p3),
从1开始计数排好序。从所有子元素中开始选
2,①第index个元素还要必须符合childselector
结论:这两个条件都要符合, 有一个不符合就选不中。
例如:p:nth-child(2) 1,第2个,2,必须是p元素
例如:p:nth-child(1) 1,第1个不是p元素 就选不中
childselector:nth-of-type(index)
1,子选择器(childselector,这里是p选择器)选中元素的父级元素ul,
得到符合子选择器(childselector)子元素(包括自己和符合子选择器(childselector)兄弟元素)
(p1,p2,p3),从1开始计数排好序。从所有子元素中开始选
2,①第index个元素②还要必须符合childselector。结论:这两个条件都要符合, 有一个不符合就选不中。
p:nth-child(1) 第1个 必须是p元素 选中p1
p:nth-child(2) 第2个 必须是p元素 选中p2

简短理解

childselector:nth-child(index)
1,childselector元素父元素所有子元素,开始index1开始计数
2,childselector, index:两个约束的地方
childselector:nth-of-type(index)
1,childselector元素父元素childselector子元素,开始index1开始计数
2,childselector, index:两个约束的地方


nth的中文意思
形容词(一系列事物中)第 n 次的,第 n 位的
The story was raised with me for the nth time two days before the article appeared
在我第n次被问及这件事情的两天后,相关文章登了出来。 ----柯林斯高阶英汉双解学习


扩展

:first-child :last-child :only-child :nth-child(n) :nth-last-child(n)
:first-type :last-type :only-type :nth-of-type(n) :nth-last-type(n)

例子

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <style>
        /* 
        这个选择不中
        原因参考http://www.cnblogs.com/leee/p/7275860.html
        li:nth-child(2) {
            color: green;
        } */
        p:nth-child(2) {
            color: green;
        }
        li:nth-of-type(2) {
            color: red;
        }
       
    </style>
</head>

<body>
    <ul>
        <li>li1</li>
        <p>p1</p>
        <li>li2</li>
        <p>p2</p>
        <li>li3</li>
    </ul>
</body>

</html>

原文地址:https://www.cnblogs.com/leee/p/7275860.html