颠覆网络35天 ─ nth-* Firefox 3.5中全新的CSS属性
12 August 2009原文地址:new CSS3 properties in Firefox 3.5 – nth-*
系列地址:颠覆网络35天
====================================
Firefox 3.5支持一些全新的CSS3选取器。在这篇文章中,我们会介绍其中的四个::nth-child,:nth-last-child,:nth-of-type 和 :nth-last-of-type。
这些选取器也被称作伪类,可以为已有的选取器增加风格。我们来看一些实际的例子。
这个伪类允许为一组元素添加风格。最常见的例子就是在表格中隔行高亮数据单元格:
tr:nth-child(even) { background-color: #E8E8E8; }
实际的例子(需要Firefox 3.5):
| Row 1 |
| Row 2 |
| Row 3 |
| Row 4 |
还可以使用特殊的标记来为超过两组元素添加风格。文档中对规则的描述不太准确,但是在例子中的“3”把元素分为三组,“+1”则是在组中的偏移量。在规范中还有很多例子。
tr:nth-child(3n+1) { background-color: red; } tr:nth-child(3n+2) { background-color: green; } tr:nth-child(3n+3) { background-color: blue; }
实际的例子(需要Firefox 3.5):
| Row 1 |
| Row 2 |
| Row 3 |
| Row 4 |
| Row 5 |
| Row 6 |
:nth-last-child伪类同:nth-child的工作方式非常相似,不过他是从后向前数子节点:
tr:nth-last-child(3n+3) { background-color: red; } tr:nth-last-child(3n+2) { background-color: green; } tr:nth-last-child(3n+1) { background-color: blue; }
例子(需要Firefox 3.5):
| Row 1 |
| Row 2 |
| Row 3 |
| Row 4 |
| Row 5 |
| Row 6 |
:nth-of-type伪类使用跟其他伪类类似的语法,但是允许你根据元素类型进行选取。
div:nth-of-type(odd) { border-color: red } div:nth-of-type(even) { border-color: blue }
例子(需要Firefox 3.5):
I should be red!
I should be blue!
:nth-last-of-type同:nth-of-type功能类似,不过也是从后向前查子节点。
No comments yet