区分nth-child(n)等结构化伪类
来源:互联网 发布:诸暨市行知小学的资料 编辑:程序博客网 时间:2024/05/17 02:03
引言
css选择器看似很多,其实对他们进行分类的话无非几种。为了加强css选择器的灵活性和减少HTML代码量,css还为我们提供了伪类和伪元素。其中伪类还分为两大类:UI状态伪类和结构化伪类。
常见的结构化伪类如:nth-chlid、first-child、nth-of-type等,由于长的相似、功能相似,对于初学者容易混淆,看到的时候知其作用但需要用到的时候不知其具体怎么写,还得查看文档而减低效率。假如对其作总结,不难发现,关于结构化伪类可以分成这样两种形式:xxx-child和xxx-of-type。1、形如xxx-child的伪类(5个)
:first-child
:last-child
:only-child
:nth-child(n)
:nth-last-child(n)
2、形如xxx-of-type的伪类(5个)
:first-of-type
:last-of-type
:only-of-type
:nth-of-type(n)
:nth-last-of-type(n)
xxx-child伪类说明
在5个xxx-child伪类中,最为关键的是nth-child,其他的几个在我看来只是他的变形。所以,只要理解nth-child,其他几个伪类也就清楚了。
nth-child的语法如下:
element:nth-child(n)其中n可以是数字、标识符和公式。
语义:匹配任意element,该element必须是其父元素的第n个子元素;否则不匹配。
假如现在有这么一个需求:有4个<li>,把第二个<li>的背景色设置成#0ff。
利用nth-child我们可以这么写代码:
<ul><li>我是第一个list-item</li><li>我是第二个list-item</li><li>我是第三个list-item</li><li>我是第四个list-item</li></ul>
li:nth-child(2) {background-color: #0ff;}这么写的好处是我们不需要在HTML代码中为第二个<li>设置任何的属性。那么,li:nth-child(2)是什么意思呢。
根据上述语义说明,li:nth-child(2)匹配了任意的<li>元素,且该<li>恰好是其父元素(ul)的第二个子元素。由于其他的三个<li>不是其父元素的第二个子元素,所以不能匹配样式。
了解nth-child后,其他几个伪类就可以这样理解:
:first-child 等同于 :nth-child(1)
:last-child 等同于 :nth-child(4) :这里的4是根据上面的实例得来的,上面的例子中最后一个<li>是其父元素的第四个子元素。
element:last-child 其实就是匹配任意element,该element还必须是其父元素的最后一个子元素。
:only-child
element:only-child 匹配任意element,该element必须是其父元素唯一的子元素。
:nth-last-child 其实就是nth-child的颠倒。 li:nth-last-child(1) 等同于 li:nth-child(4)、li:nth-last-child(2) 等同于 li:nth-child(3)...
xxx-of-child伪类说明
element:nth-of-type(n)其中n可以是数字、关键字或公式。
代码1:
li:nth-of-type(2) {background-color: #0ff;}
<ul><li>我是第一个list-item</li><p>我是一个p</p><li>我是第二个list-item</li><li>我是第三个list-item</li><li>我是第四个list-item</li></ul>实现的效果:
代码2:
li:nth-child(2) {background-color: #0ff;}
<ul><li>我是第一个list-item</li><p>我是一个p</p><li>我是第二个list-item</li><li>我是第三个list-item</li><li>我是第四个list-item</li></ul>实现的效果:
通过上面的两个代码可以更容易的看出 nth-of-type 和 nth-child 两者的区别:li:nth-of-type(2) 匹配到了ul中的第二个<li>,该<li>是其父元素(ul)的第二个<li>子元素;而li:nth-child(2)没有匹配到任何元素,因为实例中所有的<li>都不是其父元素的第二个子元素。
- 区分nth-child(n)等结构化伪类
- nth-child(n)和nth-of-type(n)的区分
- css3:nth-child(n):
- css3: nth-child(n)解析
- 巧用nth-last-child(n)
- 伪类选择器之结构选择器::noth-child(n)/:nth-of-type(n)
- css中的first-child nth-child nth-last-child() 和:nth-of-type(n)
- :nth-child(n)与:nth-of-type(n)的区别
- nth-type-of nth-child(n) eq(n)区别
- :nth-child(n)与:nth-of-type(n)的区别
- css nth-child(n)和nth-of-type(n)区别
- 样式中 nth-child(n) 的用法
- :nth-child(n)选择器实现隔行控制
- css学习选择器之:nth-child(n)
- nth-child(n)的IE8兼容问题
- JQuery_JQuery选择器(:nth-child(n))详解
- 使用CSS3 :nth-child(n) 選取器教學
- 选择器——:nth-last-child(n),
- iScroll5实现上拉加载下拉刷新
- Linux任务前后台的切换
- 静态导入
- Android----ViewPager页面滑动基础--PagerAdapter篇(二)
- jeebbsv5 源码在本地运行可能遇到的相关问题
- 区分nth-child(n)等结构化伪类
- nginx配置访问密码,让用户输入用户名密码才能访问
- css32d与3d的方法
- c++ fatal error LNK1561: 必须定义入口点
- c#处理3种json数据的实例
- 这个陌生的城市遇到了你
- python正则表达式(3)
- ubuntu16.04下使用自带Remmina控制别的ubuntu机器的方法
- C#解析json