:nth-child和:nth-of-type
来源:互联网 发布:淘宝神笔卖家推荐 编辑:程序博客网 时间:2024/05/16 09:25
在使用css的选择器中,经常会使用匹配到特定某个子元素,于是就想到了:nth-child和:nth-of-type。那么这两种到底有什么区别呢
定义
在MDN中的定义:
:nth-child(an+b) 这个 CSS 伪类匹配文档树中在其之前具有 an+b-1 个兄弟节点的元素,其中 n 为正值或零值。简单点说就是,这个选择器匹配那些在同系列兄弟节点中的位置与模式 an+b 匹配的元素。
(注意看两种定义的斜体字部分)
:nth-of-type(an+b) 这个 CSS 伪类 匹配那些在它之前有 an+b-1 个相同类型兄弟节点的元素,其中 n 为正值或零值。
:nth-child 只强调了同系列兄弟节点位置的关系
这个选择器匹配那些在同系列兄弟节点中的位置
:nth-of-type 则是更加精确到元素的类型
匹配那些在它之前有 an+b-1 个相同类型兄弟节点的元素
使用
:nth-child
<!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>nth</title> <style> p:nth-child(1) { color:red; } p:nth-child(2) { color:blue; } p:nth-child(3) { color:pink; } </style></head><body> <div class="content"> <p>1</p> <div class="app">app</div> <p>1</p> <p>1</p> <p>1</p> <p>1</p> <p>1</p> </div></body></html>
效果如下:
可以看到,当p标签中间插入了别的标签时,兄弟节点的位置会发生变化,就会影响匹配到的内容。
:nth-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>nth</title> <style> p:nth-of-type(1) { color:red; } p:nth-of-type(2) { color:blue; } p:nth-of-type(3) { color:pink; } </style></head><body> <div class="content"> <p>第一个P</p> <div class="app">app</div> <p>第二个P</p> <p>第三个P</p> <p>第四个P</p> <p>第五个P</p> <p>第六个P</p> </div></body></html>
效果如下:
虽然兄弟节点位置发生变化,但在精确匹配到类型之后,还是可以选中所需要的DOM元素。
个人认为一般情况下还是使用:nth-of-type比较靠谱
阅读全文
0 0
- nth-child和nth-of-type区别
- 浅谈:nth-child和:nth-of-type
- :nth-child和:nth-of-type
- css中的first-child nth-child nth-last-child() 和:nth-of-type(n)
- :nth-child 和 :nth-type-of 的区别
- :nth-child 和 :nth-type-of 的区别
- CSS3中:nth-child和:nth-of-type的区别
- CSS3中:nth-child和:nth-of-type的区别
- :nth-child和:nth-of-type的区别
- 关于:nth-child和:nth-of-type的区别
- :nth-child和:nth-of-type的区别
- CSS3—nth-child()和nth-of-type()
- CSS 关于nth-child和nth-of-type
- nth-child(n)和nth-of-type(n)的区分
- nth-child和nth-of-type的区别
- :nth-child和:nth-of-type的区别
- nth-of-type和nth-child的区别
- css3之nth-child和nth-of-type
- libcurl增加HTTP header 和 POST之后获取返回数据
- Selenuim+Python之元素定位总结及实例说明
- ContOS 7.2安装
- JAVA内存管理(三)- JVM内存管理及垃圾回收
- Duilib 源码分析之 CResourceManager 篇
- :nth-child和:nth-of-type
- 一元二次方程
- ListView—Adapter的使用
- Ubuntu 16.04下Intel SGX应用程序程序开发——获得Enclave函数返回值!
- Spark JVM调优 --GC
- VS代码调试运行中的错误
- Mac下提示APP已损坏,打不开,请移至废纸篓
- 05_c++构造和析构
- 简单ssh注解模式搭建