iT邦幫忙

2024 iThome 鐵人賽

DAY 19
0

nth-last-child

前面我們講到過 :last-child,它可以直接選中同層的最後一個元素,而 :nth-last-child 則讓我們能從最後開始計算,選取倒數的元素,這對於快速選取倒數幾個元素非常方便。同樣地,除了選取所有元素外,我們還有 :nth-last-of-type,可以專門選取同類型的元素。

💠:nth-last-child 基本用法

語法

選擇器:nth-of-type(n) {
	屬性名: 屬性值;
}
  • 選中所有兄弟元素中的倒數第 n 個

範例

一起試試:[CODEPEN]

選中 .outer 中倒數第三個且為 <p> 的元素

<div class="outer">
  <p class="box">p</p>
  <p class="box">p</p>
  <p class="box">p</p>
  <div class="box">div</div>
  <div class="box">div</div>
  <p class="box">p</p>
  <p class="box">p</p>
  <p class="box">p</p>
  <div class="box">div</div>
  <div class="box">div</div>
</div>
.outer p:nth-last-child(3) {
  background-color: skyblue;
}

nth-last-child

倒數第三個 <p> 元素背景色將會變成 skyblue

如果現在想選中倒數第二個呢?我們把條件改成 2

.outer p:nth-last-child(2) {
  background-color: skyblue;
}

但這時不會選中任何元素

nth-last-child

為什麼呢?

這是因為倒數第二個元素並非<p>元素,所以我們可以直接選取倒數第二個所有子元素

.outer > :nth-last-child(2) {
  background-color: skyblue;
}

如此一來,將會選取 .outer 裡所有元素中倒數第 2 個直接子元素

如果想針對類型,選取所有 <p> 元素中倒數第二個 <p> 元素,你可以使用 :nth-last-of-type

💠:nth-last-of-type 基本用法

語法

選擇器:nth-last-of-type(n) {
	屬性名: 屬性值;
}
  • 選中所有同類型兄弟元素中的倒數第 n 個

範例

一起試試:[CODEPEN]

選中 .outer 中倒數第二個 <p> 元素

<div class="outer">
  <p class="box">p</p>
  <p class="box">p</p>
  <p class="box">p</p>
  <div class="box">div</div>
  <div class="box">div</div>
  <p class="box">p</p>
  <p class="box">p</p>
  <p class="box">p</p>
  <div class="box">div</div>
  <div class="box">div</div>
</div>
.outer p:nth-last-of-type(2) {
  background-color: gold;
}

nth-last-of-type

將會選中 .outer 中倒數第二個 <p> 元素,而不會影響其他類型的元素。

如果沒有指定類型,將會選中所有類型倒數第二個元素

.outer > :nth-last-of-type(2) {
  background-color: gold;
}

nth-last-of-type


💠總結

:nth-last-child:nth-last-of-type 提供了一種靈活的方式,讓我們可以從後往前選取元素。前者不限制元素類型,適合快速選取不同類型的倒數元素;而後者則專門針對同類型的元素,提供更精確的選取能力。這兩個選擇器能夠滿足我們在排版中對元素的精細操作需求。


上一篇
:nth-of-type 針對類型元素任你挑
下一篇
:only-child & :only-of-type 讓唯一的元素成為焦點
系列文
你的優先選擇是什麼?從 CSS 選擇器到優先級,深入解析與實用技巧29
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言