CSS伪类 :nth-last-child() 根据元素在一组兄弟姐妹中的位置匹配元素,从最后开始计算。
语法
可能的值
- 奇数 − 此值表示从末尾开始计数的系列中的所有奇数(例如,1,3,5..etc)同级元素。
- 偶数 − 此值表示从末尾开始计数的系列中的所有偶数(例如,2,4,6...等)同级元素。
- 函数表示法 (<an+b>) − 此值表示从其父容器的末尾开始计数的序列中的每个 an+b 子元素,其中 a 是正整数,n 是从 0 开始的计数器变量。b 是另一个正整数。
下表描述了 CSS 选择器的列表及其说明:
选择器 | 描述 |
---|---|
tr:nth-last-child(odd) or tr:nth-last-child(2n+1) | 表示 HTML 表中的所有奇数行。 |
tr:nth-last-child(even) or tr:nth-last-child(2n) | 表示 HTML 表中的所有偶数行。 |
:nth-last-child(6) | 代表第六个元素,从末尾开始计算。 |
:nth-last-child(5n) | 表示每五个元素(5、10、15 等),从末尾开始计数。 |
:nth-last-child(3n+4) | 代表元素 4、7、10、13 等,从末尾开始计数。 |
:nth-last-child(-n+2) | 表示一组同级产品中的最后两个元素。 |
p:nth-last-child(n) or p:nth-last-child(n+1) | 表示一组同级<p>元素。 |
p:nth-last-child(1) or p:nth-last-child(0n+1) | 表示一组兄弟姐妹中的第一个元素的每个 <p>,从末尾开始计数。 |
CSS :nth-last-child() - 列表示例
下面是一个示例,说明如何在 ol 列表中设置 li 元素的样式 -
CSS :nth-last-child() - 表格示例
下面是一个示例,如何为表中的特定行设置样式 -
CSS :nth-last-child() - 段落示例
以下是如何设置段落样式的示例 -
CSS :nth-last-child() - <选择器>
带有 <selector> 元素的 :nth-last-child() 伪类的语法:
将选择器 li.fruits 移到函数外部将选择具有 fruits 类的所有 li 元素,无论它们在子元素列表中的位置如何。
下面是一个示例,说明如何使用 :nth-last-child(even of .fruits) 伪类来表示类为 .fruits 的特定项目−