CSS3的:nth选择器的几种用法

admin2023-01-192564

:first-child选择某个元素的第一个子元素;

:last-child选择某个元素的最后一个子元素;

:nth-child()选择某个元素的一个或多个特定的子元素;

:nth-last-child()选择某个元素的一个或多个特定的子元素,从这个元素的最后一个子元素开始算;

:nth-of-type()选择指定的元素;

:nth-last-of-type()选择指定的元素,从元素的最后一个开始计算;

:first-of-type选择一个上级元素下的第一个同类子元素;

:last-of-type选择一个上级元素的最后一个同类子元素;

:only-child选择的元素是它的父元素的唯一一个了元素;

:only-of-type选择一个元素是它的上级元素的唯一一个相同类型的子元素;

:empty选择的元素里面没有任何内容。

1、:first-child

.demo li:first-child {background: green; border: 1px dotted blue;}
.demo li.first {background: green; border: 1px dotted blue;}

2、:last-child

.demo li:last-child {background: green; border: 2px dotted blue;}
.demo li.last {background: green; border: 2px dotted blue;}

3、:nth-child()

:nth-child(length);/*参数是具体数字*/ 
:nth-child(n);/*参数是n,n从0开始计算*/
:nth-child(n*length)/*n的倍数选择,n从0开始算*/ 
:nth-child(n+length);/*选择大于length后面的元素*/ 
:nth-child(-n+length)/*选择小于length前面的元素*/
:nth-child(n*length+1);/*表示隔几选一*/ 
 //上面length为整数

.demo li:nth-child(3) {background: lime;}

这种不式不能引用负值,也就是说li:nth-child(-3)是不正确的使用方法。

:nth-child(2n),这中方式是前一种的变身,我们可以选择n的2倍数,当然其中“2”可以换成你自己需要的数字
.demo li:nth-child(2n) {background: lime;}
 等于
.demo li:nth-child(even) {background: lime;}

:nth-child(-n+5)这种选择器这个是选择第5个前面的

n=0 --》 -n+5=5 --》 选择了第5个li
n=1 --》 -n+5=4 --》 选择了第4个li
n=2 --》 -n+5=3 --》 选择了第3个li
n=3 --》 -n+5=2 --》 选择了第2个li
n=4 --》 -n+5=1 --》 选择了第1个li
n=5 --》 -n+5=0 --》 没有选择任何元素

4、:nth-last-child()

.demo li:nth-last-child(4) {background: lime;}

5、:nth-of-type

:nth-of-type类似于:nth-child,不同的是他只计算选择器中指定的那个元素

6、:nth-last-of-type

这个选择器不用说大家都能想得到了,他和前面的:nth-last-child一样使用,只是他指定的元素类型而以。

7、:first-of-type和:last-of-type

:first-of-type和:last-of-type这两个选择器就类似于:first-child和:last-child;不同之处就是指定了元素的类型。

8、:only-child和:only-of-type

":only-child"表示的是一个元素是它的父元素的唯一一个子元素。

9、:empty

:empty是用来选择没有任何内容的元素,这里没有内容指的是一点内容都没有,哪怕是一个空格,比如说,你有三个段落,其中一个段落什么都没有,完全是空的,你想这个p不显示

10、:not

否定选择器和jq中的:not选择器一模一样,就拿form中的元素来说明这个选择器的用法,比如你想对form中所有input加边框,但又不想submit也起变化,此时就可以使用:not为实现。

:not(p){         //设置非 <p> 元素的所有元素的背景色:
background-color: #ff0000;
}


网友评论