:nth选择器 登录

:nth选择器

此选择器能够实现对元素的精准匹配元素,主要有:

:fist-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

   :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;}

css3-selector-nth1.png

2、:last-child

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

css3-selector-nth2.png

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;}

css3-selector-nth3.png

这种不式不能引用负值,也就是说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;}

css3-selector-nth10.png

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不显示



下一节
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.php.cn/" /> <title>php中文网</title> <style type="text/css"> li:first-child{ color:green; } </style> </head> <body> <ul> <li>html专区</li> <li>Div+css专区</li> <li>Jquery专区</li> <li>Javascript专区</li> </ul> </body> </html>
提交 重置代码
章节 评论 笔记 课件
  • 取消 回复 发送
  • 取消 发布笔记 发送