分享好友 教程首页 教程搜索 频道列表

CSS选取第几个标签元素:nth-child(n)、first-child、last-child

2023-04-12 12:373450
+关注2
核心提示:CSS选取第几个标签元素:nth-child(n)、first-child、last-child,nth-child(n)、...

CSS选取第几个标签元素:nth-child(n)、first-child、last-child

nth-child(n)、first-child、last-child用法

注:nth-child(n)选择器匹配父元素中的第n个子元素。 

n可以是一个数字,一个关键字,或者一个公式。


nth-child(n)用法: 

1、nth-child(3) 

表示选择列表中的第3个标签,代码如下:

li:nth-child(3){background:#fff}


2、nth-child(2n) 

表示选择列表中的偶数标签,即选择 第2、第4、第6…… 标签,代码如下:

li:nth-child(2n){background:#fff}


3、nth-child(2n-1) 

表示选择列表中的奇数标签,即选择 第1、第3、第5、第7……标签,代码如下:

li:nth-child(2n-1){background:#fff}


4、nth-child(n+3) 

表示选择列表中的标签从第3个开始到最后,代码如下:

li:nth-child(n+3){background:#fff}


5、nth-child(-n+3) 

表示选择列表中的标签从0到3,即小于3的标签,代码如下:

li:nth-child(-n+3){background:#fff}

 

6、nth-last-child(3) 

表示选择列表中的倒数第3个标签,代码如下

li:nth-last-child(3) a


7、nth-last-child(n+3) 

表示选择列表中的倒数第3个标签及之前的标签,代码如下:

li:nth-last-child(n+3) a


8、nth-last-child(-n+3) 

表示选择列表中的倒数后3个标签,代码如下:

li:nth-last-child(-n+3) a

 


first-child用法: 

1、first-child 

first-child表示选择列表中的第一个标签。代码如下:

li:first-child{background:#fff}



last-child用法: 

1、last-child 

last-child表示选择列表中的最后一个标签,代码如下:

li:last-child{background:#fff}

 

:nth-child(2)选取第几个标签,“2可以是你想要的数字”

.demo01 li:nth-child(2){background:#090}


:nth-child(n+4)选取大于等于4标签,“n”表示从整数,下同

.demo01 li:nth-child(n+4){background:#090}


:nth-child(-n+4)选取小于等于4标签

.demo01 li:nth-child(-n+4){background:#090}


:nth-child(2n)选取偶数标签,2n也可以是even

.demo01 li:nth-child(2n){background:#090}

 

:nth-child(2n-1)选取奇数标签,2n-1可以是odd

.demo01 li:nth-child(2n-1){background:#090}

 

:nth-child(3n+1)自定义选取标签,3n+1表示“隔二取一”

.demo01 li:nth-child(3n+1){background:#090}


:last-child选取最后一个标签

.demo01 li:last-child{background:#090}


:nth-last-child(3)选取倒数第几个标签,3表示选取第3个

.demo01 li:nth-last-child(3){background:#090}


一些常用的css伪类选择语法:

n2n+14n+14n+44n5n-2-n+3
0114--3
1358432
25912881
3713161213-
4917201618-
51121242023-
本文标签: #nth-child #first-child #last-child
整理员:网络转载
免责声明:凡注明来源本网的所有作品,均为本网合法拥有版权或有权使用的作品,欢迎转载,注明出处。非本网作品均来自互联网,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。
生成海报
您可能在找更多

CSS选取第几个标签元素:nth-child(n)、first-child、last-child

    今天码代码时候遇到的需求要选取前两个标签元素,查了资料记录下来~

网络转载 CSS相关2020-07-27

CSS3选择器nth-child(n)实现隔几行选择元素

    nth-child(n),n 可以是数字、关键词或公式。选择器匹配属于其父元素的第N个子元素,不论元素的类型。序号写法:1. li:nth-child(3){background:orange;}倍数写法:1. li:nth-child(3n){background:orange;}倍数分组匹配:1. li:nth-child(3n+1){background:orange;}2. li:nth-child(3n+5){background:orange;}3. li:nth-child(5n-1){ba

小黑 CSS相关2019-05-17

下一篇
我来说两句
抢沙发