--- title: ':nth-last-child' slug: 'Web/CSS/:nth-last-child' tags: - ':nth-child' - ':nth-last-child' - 伪类 translation_of: 'Web/CSS/:nth-last-child' ---
:nth-last-child()
这个CSS 伪类 从兄弟节点中从后往前匹配处于某些位置的元素
/* 在所有兄弟节点中,从后往前 选择所有4的倍数的节点 */ :nth-last-child(4n) { color: lime; }
注意: 这个伪类和 {{Cssxref(":nth-child")}} 基本一致, 但它是从结尾计数, 而不是从开始计数.
nth-last-child
伪类接受一个参数, 用来作为一个模式,从后往前匹配元素.
odd
even
<An+B>
An+B
, n
是0或者任意的正整数. 从结尾开始计算的第一个元素的索引值是1
. A
和 B
必须都是 {{cssxref("<integer>")}}.{{csssyntax}}
tr:nth-last-child(odd)
or tr:nth-last-child(2n+1)
tr:nth-last-child(even)
or tr:nth-last-child(2n)
:nth-last-child(7)
:nth-last-child(5n)
:nth-last-child(3n+4)
:nth-last-child(-n+3)
p:nth-last-child(n)
or p:nth-last-child(n+1)
<p>
元素。这与一个简单的p
选择器相同。(由于n
从0开始,而最后一个元素从1开始,n
和n+1
都会选择相同的元素。)p:nth-last-child(1)
or p:nth-last-child(0n+1)
<p>
。这与{{cssxref(":last-child")}}选择器相同。<table> <tbody> <tr> <td>First line</td> </tr> <tr> <td>Second line</td> </tr> <tr> <td>Third line</td> </tr> <tr> <td>Fourth line</td> </tr> <tr> <td>Fifth line</td> </tr> </tbody> </table>
table { border: 1px solid blue; } /* Selects the last three elements */ tr:nth-last-child(-n+3) { background-color: pink; } /* Selects every element starting from the second to last item */ tr:nth-last-child(n+2) { color: blue; } /* Select only the last second element */ tr:nth-last-child(2) { font-weight: 600; }
{{EmbedLiveSample('Table_example', 300,150)}}
数量查询样式元素取决于它们的数量。在本例中,当给定列表中至少有三个列表项时,列表项变为红色。这是通过组合nth-last-child
和 通用兄弟选择器.的功能来实现的
<h4>A list of four items (styled):</h4> <ol> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> </ol> <h4>A list of two items (unstyled):</h4> <ol> <li>One</li> <li>Two</li> </ol>
/* If there are at least three list items, style them all */ li:nth-last-child(n+3), li:nth-last-child(n+3) ~ li { color: red; }
{{EmbedLiveSample('Quantity_query', '100%', 270)}}
Specification | Status | Comment |
---|---|---|
{{ SpecName('CSS4 Selectors', '#nth-last-child-pseudo', ':nth-last-child') }} | {{ Spec2('CSS4 Selectors') }} | No change. |
{{ SpecName('CSS3 Selectors', '#nth-last-child-pseudo', ':nth-last-child') }} | {{ Spec2('CSS3 Selectors') }} | Initial definition. |
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
{{Compat("css.selectors.nth-last-child")}}