一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

CSS3伪类选择器:nth-child()用法详解

时间:2016-10-19 编辑:简简单单 来源:一聚教程网

CSS3的出现无疑给前端开发人员带来了巨大的优势,今天我们着重介绍CSS3中一个新出现的强大伪类选择器:nth:child();为了方便大家理解,我今天会通过展示曾经做过的项目页面,让大家直观清晰的了解这一伪类选择器的功能和使用技巧

 

1.首先大家了解下该伪类的语法法:       :nth-child(an+b)

ps:可惜的是该伪类选择器不支持ie浏览器,当要兼容ie浏览器的时候,我们只有每一个li给它们添加类名了

2.这是我们要实现的页面效果

 


步骤一:

先写好html代码

添加样式

.topone-ul {
margin: 0 auto;
margin-top: 60px;


}
.toponeul li {
float: left;
margin-right: 40px;

height: 100%;
text-align: center;
}
.toponeul li:nth-child(5) {
margin-right: 0px;
}
.toponeul li a {
color: #fff;
line-
}
从代码中可以看出我们用的是

  • 标签,其中每一个li中的图标我是用的雪碧图,整体放在一张图片中,作为背景图,通过移动位置,添加到对应得li中,

    现在要把该雪碧图作为背景图放到每一个

  • 中,该怎么办呢???

    是要给每一个

  • 都添加一个类名吗??这样太麻烦啦!

    现在我们就有一个很好地办法,利用CSS3中:nth-child()来给每一

  • 中添加背景

    1.首先第一个

  • 中放入背景可以这样写


    .toponeul li:nth-child(1) .topone-img {
    margin: 0 auto;


    background: url(../images/high/sprite.png) no-repeat;
    background-position: -44px 0px;
    }
    :nth-child(1)指的就是.toponeul下面的第一

  • 以此类推:第二个,第三个,第四个,第五个

    .toponeul li:nth-child(2) .topone-img {
    margin: 0 auto;


    background: url(../images/high/sprite.png) no-repeat;
    background-position: -68px 0px;
    }
    .toponeul li:nth-child(3) .topone-img {
    margin: 0 auto;


    background: url(../images/high/sprite.png) no-repeat;
    background-position: -91px 0px;
    }
    .toponeul li:nth-child(4) .topone-img {
    margin-left: 15px;


    background: url(../images/high/sprite.png) no-repeat;
    background-position: 4px 0px;
    }
    .toponeul li:nth-child(5) .topone-img {
    margin: 0 auto;


    background: url(../images/high/sprite.png) no-repeat;
    background-position: -19px 0px;
    }

    下面介绍下此伪类选择器的第二种写法:倍数写法

    语法:       :nth-child(an)


    如li:nth-child(3n)、li:nth-child(5n)、li:nth-child(2n)············分别指3倍、5倍、2倍的li。
    例如:


    li:nth-child(3n){background:#000;} 意思是把第3、第6、第9、…、所有3的倍数的li的背景设为黑色
    下面介绍下此伪类选择器的第三种写法:倍数分组匹配

    语法 :          :nth-child(an+b) 与 :nth-child(an-b)

    例子:


    li:nth-child(3n+1){background:#000;}        意思是把第1、第4、第7、…、每3个为一组的第1个LI的背景设为黑色
     
    li:nth-child(3n+5){background:#000;}        意思是把 第5、第8、第11、…、从第5个开始每3个为一组的第1个LI的背景设为黑色
     
    li:nth-child(5n-1){background:#000;}         意思是把第5-1=4、第10-1=9、…、第5的倍数减1个LI的背景设为黑色
     
    li:nth-child(3n±0){background:#000;}         相当于(3n)的背景设为黑色
     
    li:nth-child(±0n+3){background:#000;}       相当于(3)的背景设为黑色
    下面介绍下此伪类选择器的第五种用法:奇偶匹配

    语法:          :nth-child(odd) 与 :nth-child(even)

    分别匹配序号为奇数与偶数的元素。奇数(odd)与(2n+1)结果一样;偶数(even)与(2n+0)及(2n)结果一样。

    表格奇偶数行定义样式就可以写成


    .table > tr:nth-child(even) > td {background-color: #000;}  (偶数行)意思是把第2、第4、第6、…、每2个为一组的LI的背景设为黑色
    .table > tr:nth-child(odd) > td {background-color: #000;}  (奇数行) 意思是把第1、第3、第5、…、每2个为一组的LI的背景设为黑色
    好了,现在是不是对CSS3:        :nth-child()伪类选择器已经很理解了呢,现在大家可以快捷又方便的实现自己想要的效果了!

    热门栏目