:last-of-type

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

:last-of-type CSS 偽類表示在一組同級元素中,其型別(標籤名)是最後一個的元素。

試一試

dt {
  font-weight: bold;
}

dd {
  margin: 3px;
}

dd:last-of-type {
  border: 2px solid orange;
}
<dl>
  <dt>Vegetables:</dt>
  <dd>1. Tomatoes</dd>
  <dd>2. Cucumbers</dd>
  <dd>3. Mushrooms</dd>
  <dt>Fruits:</dt>
  <dd>4. Apples</dd>
  <dd>5. Mangos</dd>
  <dd>6. Pears</dd>
  <dd>7. Oranges</dd>
</dl>

語法

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

示例

設定最後一個段落的樣式

HTML

html
<h2>Heading</h2>
<p>Paragraph 1</p>
<p>Paragraph 2</p>

CSS

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

結果

巢狀元素

此示例展示瞭如何定位巢狀元素。請注意,當沒有編寫簡單選擇器時,會隱式使用通用選擇器 (*)。

HTML

html
<article>
  <div>This `div` is first.</div>
  <div>This <span>nested `span` is last</span>!</div>
  <div>
    This <em>nested `em` is first</em>, but this <em>nested `em` is last</em>!
  </div>
  <p>This `p` qualifies!</p>
  <div>This is the final `div`!</div>
</article>

CSS

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

結果

多個選擇器元素

此 HTML 示例包含不同型別的巢狀元素。CSS 包含型別選擇器和類選擇器。

HTML

html
<p>This `p` is not selected.</p>
<p>This `p` is not selected either.</p>
<p>
  This `p` is last `p` element of its parent e.g. `body` selected by `p` type
  selector.
</p>
<div class="container">
  <div class="item">This `div` is not selected.</div>
  <div class="item">This `div` is not selected either.</div>
  <div class="item">
    This `div` is last `div` element of its parent `div` selected by `.container
    .item` class selector.
  </div>
  <p class="item">
    This `p` is last `p` element of its parent `div` selected by `.container
    .item` class selector.
  </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 類。

規範

規範
選擇器 Level 4
# last-of-type-偽類

瀏覽器相容性

另見