CSS的nth-child使用方法
当我想要完美的使用:nth-child或者:nth-of-type的时候有点儿头晕。你越理解它们,就能写出越好的CSS规则!
在这些简单的“秘方“(实际上是表达式)中我将重复的使用一个简单的列表并随即选择数字。但是很明显很容易改变它们以获得类似的选择器。
只选择第五个元素

li:nth-child(5){
color: green;
}
要选择第一个元素,你可以使用:first-child,或者我相信你也可以改下上面的例子来实现。
选择除了前面的五个之外的所有元素

如果有超过10个元素,它将会选中超过5个。
只选择前面的5个

li:nth-child(-n+5){
color: green;
}
从开始的那个,选择每第四个

li:nth-child(4n-7) {
/* or 4n+1 */
color: green;
}
选择奇数或者偶数

li:nth-child(odd){
color: green;
}

li:nth-child(even){
color: green;
}
当然这里也有另外两种实现,你懂的——神飞
选择最后一个元素

li:last-child {
color: green;
}
选择倒数第二个

li:nth-last-child(2){
color: green;
}
从这个例子可看出,上面那个例子也有第二种实现方法。
浏览器支持
有趣的是,:first-child 和:last-child被IE 7支持,但是知道IE9才支持剩下的选择器。如果你担心IE,可以使用Selectivizr。如果你浏览器兼容性对你很重要,请关注When can I use…
嗯,使用CSS3选择器是件很有趣的事情,像做简单的数学题一样。
li:nth-child(n+6){
color: green;
}
本文网址:https://www.dedexuexi.com/divcss/jc/1889.html
本站部分文章搜集与网络,如有侵权请联系本站,转载请说明出处。