:last-of-type

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.

:last-of-typeCSS擬似クラスで、兄弟要素のグループの中でその種類の最後の要素を表します。

試してみましょう

構文

css
:last-of-type {
  /* ... */
}

最後の段落の整形

HTML

html
<h2>見出し</h2>
<p>段落 1</p>
<p>段落 2</p>

CSS

css
p:last-of-type {
  color: red;
  font-style: italic;
}

結果

入れ子になった要素

この例は、入れ子になった要素を対象に含める方法を示します。なお、要素型セレクターが書かれていない場合は、全称セレクター (*) が暗黙に含まれます。

HTML

html
<article>
  <div>これは最初の `div` です。</div>
  <div>これは<span>内側で最後の `span`</span> です。</div>
  <div>
    これは<em>内側で最初の `em`</em>で、一方これは<em>最後の `em` </em>です。
  </div>
  <p>これは `p` で修飾しています。</p>
  <div>これは最後の `div` です。</div>
</article>

CSS

css
article :last-of-type {
  background-color: pink;
}

結果

複数セレクターの要素

この HTML の例では、さまざまな種類の要素が入れ子になっています。 CSS には、型セレクターとクラスセレクターの両方が含まれています。

HTML

html
<p>この `p` は選択されていません。</p>
<p>この `p` も選択されていません。</p>
<p>
  この `p` は `p` 要素型セレクターで選択された `body` などの親の最後の `p` 要素です。
</p>
<div class="container">
  <div class="item">この `div` は選択されていません。</div>
  <div class="item">この `div` も選択されていません。</div>
  <div class="item">
    この `div` は親 `div` の `.container .item` クラスセレクターで選択される最後の `div` 要素です。
  </div>
  <p class="item">
    この `p` は親 `div` の `.container .item` クラスセレクターで選択される最後の `p` 要素です。
  </p>
</div>

CSS

css
p:last-of-type {
  background: skyblue;
}

.container .item:last-of-type {
  color: red;
  font-weight: bold;
}

結果

最後の <div> と最後の <p> はどちらも赤で太字になっています。これは .item:last-of-type がすべての型の最後の要素を選択するためで、その最後の要素は item クラスも持っています。

仕様書

Specification
Selectors Level 4
# last-of-type-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
:last-of-type

Legend

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

Full support
Full support
See implementation notes.

関連情報