Fork me on GitHub

李可

导航

统计

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>

posted on   李可在江湖  阅读(486)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示