:nth-last-child()

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

* Some parts of this feature may have varying levels of support.

:nth-last-child()CSS擬似クラスで、兄弟要素のグループの中での位置に基づいて選択します。

css
/* 兄弟要素の中で、後ろから数えて
   3 つおきに要素を選択 */
:nth-last-child(4n) {
  color: lime;
}

試してみましょう

メモ: この擬似クラスは、最初から後に向けてではなく最後から前に向けて数えるという点を除けば、本質的に :nth-child と同じです。

構文

nth-last-child 擬似クラスは、要素を選択する最後から数えるパターンを表す引数を 1 つ取ります。

:nth-last-child( <nth> [ of <complex-selector-list> ]? )

キーワード値

odd

一連の兄弟要素の中で、最後から奇数番目の要素 (1, 3, 5, など) を表します。

even

一連の兄弟要素の中で、最後から偶数番目の要素 (2, 4, 6, など) を表します。

関数記法

<An+B>

一連の兄弟要素の中で、 n に正の整数か0が入るとき、 An+B のパターンに一致する位置の要素を表します。後ろから数えた最初の要素の番号は 1 です。 AB の値は両方とも <integer> です。

セレクターの例

tr:nth-last-child(odd) または tr:nth-last-child(2n+1)

HTML テーブルの最後から数えた奇数行 (1, 3, 5, など) を表します。

tr:nth-last-child(even) または tr:nth-last-child(2n)

HTML テーブルの最後から数えた偶数行 (2, 4, 6, など) を表します。

:nth-last-child(7)

最後から数えて 7 番目の要素を表します。

:nth-last-child(5n)

最後から数えて 5, 10, 15 番目などの要素を表します。

:nth-last-child(3n+4)

最後から数えて 4, 7, 10, 13 番目などの要素を表します。

:nth-last-child(-n+3)

兄弟要素のグループの中で最後の3つの要素を表します。

p:nth-last-child(n) または p:nth-last-child(n+1)

兄弟要素のグループの中ですべての <p> 要素を表します。これは単純な p セレクターと同じです。 (n はゼロから始まるので、最後の要素が1で始まり、 n および n+1 が共に同じ要素を選択します。)

p:nth-last-child(1) または p:nth-last-child(0n+1)

兄弟要素のグループの中で最初の <p> 要素すべてを表します。これは :last-child セレクターと同じです。

詳細な例

HTML

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

CSS

css
table {
  border: 1px solid blue;
}

/* 最後から 3 つの要素を選択 */
tr:nth-last-child(-n + 3) {
  background-color: pink;
}

/* 後ろから 2 番目から最初までの要素を選択 */
tr:nth-last-child(n + 2) {
  color: blue;
}

/* 後ろから 2 番目の要素のみを選択 */
tr:nth-last-child(2) {
  font-weight: 600;
}

結果

数量クエリー

数量クエリーは、要素が存在する数に応じてスタイル付けします。この例では、リストの中に項目が3つ以上ある場合にリスト項目が赤に変わります。これは nth-last-child 擬似クラスと 後続兄弟結合子の機能を組み合わせることで実現できます。

HTML

html
<h4>4 項目のリスト (スタイル付き):</h4>
<ol>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ol>

<h4>2 項目のリスト (スタイルなし):</h4>
<ol>
  <li>One</li>
  <li>Two</li>
</ol>

CSS

css
/* 3 つ以上のリスト項目がある場合、
   すべてにスタイル付けする */
li:nth-last-child(n + 3),
li:nth-last-child(3) ~ li {
  color: red;
}

結果

仕様書

Specification
Selectors Level 4
# nth-last-child-pseudo

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
:nth-last-child()
Matches elements with no parent
of <selector> syntax

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support

関連情報