在 LEA VEROU 的博客翻到这么一篇文章——《Styling children based on their number, with CSS3》。原文谈到使用“:nth-child 伪类元素选择器”的方法在 2009 年被提出,LEA VEROU 又通过普通相邻选择器(General sibling combinator[1])改良了一下。最终的代码很酷。
内容介绍
标题写的有些拗口,看看下面的例子应该可以明白。主要作用是无论父元素有多少子元素,都根据子元素的数量设定样式,而无需使用任何 class。
/* one item */
li:first-child:nth-last-child(1) {
width: 100%;
}
/* two items */
li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
width: 50%;
}
/* three items */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
width: 33.3333%;
}
/* four items */
li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
width: 25%;
}
li:first-child:nth-last-child()部分,:first-child选择了第一个子元素,:nth-last-child()用来判断这个元素属于“几个之一”。li:first-child:nth-last-child(3)即选择属于倒数第三个li的同时还是第一个元素的情况,即共 3 个子元素时的第一个。
li:first-child:nth-last-child() ~ li通过普通相邻选择器为第二个之后的所有元素设定样式[2]。
同 table 的区别
实现类似效果的方法当然不只这一种,最常用的就是表格。LEA VEROU 指出了两点不同之处:
- 表格有着特别的含义,有时并不符合我们需要的语义;
- 表格对宽度的控制没有上面的灵活(例如上面的方法可以实现子元素不完整填充父元素)。
使用范围

由于 :nth-child 直到 IE9 才被支持,所以这个技术在移动端使用更加安全。
- 本文固定链接: http://madong.net.cn/index.php/2016/07/562/
- 转载请注明: 管理员 于 小东 发表