Firefox 3.5 中新的 CSS3 属性 – nth-*

Firefox 3.5 支持几个新的 CSS3 选择器。在这篇文章中,我们将讨论其中的四个::nth-child:nth-last-child:nth-of-type:nth-last-of-type

这些都称为 伪类,可用于将样式应用于现有选择器。描述其工作原理的最佳方法是一些示例。

:nth-child

此伪类允许您将样式应用于元素组。最常见的用例是在表格中突出显示奇数或偶数项

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-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

:nth-of-type 伪类使用与这里其他元素相同的语法,但允许您根据元素类型进行选择。

div:nth-of-type(odd) { border-color: red }
div:nth-of-type(even) { border-color: blue }

示例(在 Firefox 3.5 中有效)

我应该是红色的!
我应该是蓝色的!

:nth-last-of-type

:nth-last-child 类似,:nth-last-of-type:nth-of-type 相同,只是它以相反的方向进行计数。

这四个属性允许您使用样式和元素组执行有趣的操作,我们希望它们可以使您更容易设置页面样式。


9 条评论

  1. Ed Avis

    很棒!现在是 Internet Explorer 通常的五年等待期,才能支持它……

    2009 年 6 月 25 日 上午 08:36

  2. Smooth Criminal

    不完全是,jQuery 已经支持该功能,因此随着越来越多的原生选择器被包含进来,它不应带来太多开销。

    2009 年 6 月 25 日 下午 21:40

  3. […] 原文地址:new CSS3 properties in Firefox 3.5 – nth-* 系列地址:颠覆网络35天 […]

    2009 年 6 月 25 日 下午 22:46

  4. Rizwan

    我在旧版 Firefox 中看不到更改,但这确实是个好消息。一直都在渴望 CSS3 支持。

    2009 年 6 月 26 日 上午 03:46

  5. Havvy

    对于那些不知道的人,用于选择的 cn+d 是算术序列的标准符号。d 是偏移量,c 是公差,n 是变量。

    2009 年 6 月 26 日 上午 10:09

  6. Simon Day

    这确实是好消息。希望在未来几年内我能够开始使用它。我非常讨厌 IE :-)

    我不喜欢使用 jQuery 进行样式设置的想法,因此我宁愿等到浏览器普遍支持后再完全转向它。

    2009 年 6 月 30 日 上午 02:34

  7. […] Auch werden neue Pseudoklassen unterstützt, die es dem Gestalter einer Website zum Beispiel möglich machen, die Hintergrundfarben von Tabellenzellen automatisch bestimmen zu lassen. Also […]

    2009 年 6 月 30 日 上午 11:25

  8. […] pseudo-classes: only-of-type, first-of-type and last-of-type. These are all very similar to the *-nth classes we covered in an earlier […]

    2009 年 6 月 30 日 下午 20:26

  9. […] 原文地址:new CSS3 properties in Firefox 3.5 – nth-* 系列地址:颠覆网络35天 […]

    2009 年 8 月 11 日 下午 21:58

本文评论已关闭。