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 中有效)
行 1 |
行 2 |
行 3 |
行 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 中有效)
行 1 |
行 2 |
行 3 |
行 4 |
行 5 |
行 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 中有效)
行 1 |
行 2 |
行 3 |
行 4 |
行 5 |
行 6 |
:nth-of-type
伪类使用与这里其他元素相同的语法,但允许您根据元素类型进行选择。
div:nth-of-type(odd) { border-color: red }
div:nth-of-type(even) { border-color: blue }
示例(在 Firefox 3.5 中有效)
我应该是红色的!
我应该是蓝色的!
与 :nth-last-child
类似,:nth-last-of-type
与 :nth-of-type
相同,只是它以相反的方向进行计数。
这四个属性允许您使用样式和元素组执行有趣的操作,我们希望它们可以使您更容易设置页面样式。
9 条评论