前面我們講到過 :last-child,它可以直接選中同層的最後一個元素,而 :nth-last-child
則讓我們能從最後開始計算,選取倒數的元素,這對於快速選取倒數幾個元素非常方便。同樣地,除了選取所有元素外,我們還有 :nth-last-of-type
,可以專門選取同類型的元素。
💠:nth-last-child
基本用法
語法
1 | 選擇器:nth-of-type(n) { |
- 選中所有兄弟元素中的倒數第 n 個
範例
一起試試:[CODEPEN]
選中 .outer
中倒數第三個且為 <p>
的元素
1 | <div class="outer"> |
1 | .outer p:nth-last-child(3) { |
倒數第三個 <p>
元素背景色將會變成 skyblue
如果現在想選中倒數第二個呢?我們把條件改成 2
1 | .outer p:nth-last-child(2) { |
但這時不會選中任何元素
為什麼呢?
這是因為倒數第二個元素並非<p>
元素,所以我們可以直接選取倒數第二個所有子元素
1 | .outer > :nth-last-child(2) { |
如此一來,將會選取 .outer
裡所有元素中倒數第 2 個直接子元素
如果想針對類型,選取所有 <p>
元素中倒數第二個 <p>
元素,你可以使用 :nth-last-of-type
💠:nth-last-of-type
基本用法
語法
1 | 選擇器:nth-last-of-type(n) { |
- 選中所有同類型兄弟元素中的倒數第 n 個
範例
一起試試:[CODEPEN]
選中 .outer
中倒數第二個 <p>
元素
1 | <div class="outer"> |
1 | .outer p:nth-last-of-type(2) { |
將會選中 .outer
中倒數第二個 <p>
元素,而不會影響其他類型的元素。
如果沒有指定類型,將會選中所有類型倒數第二個元素
1 | .outer > :nth-last-of-type(2) { |
💠總結
:nth-last-child
和 :nth-last-of-type
提供了一種靈活的方式,讓我們可以從後往前選取元素。前者不限制元素類型,適合快速選取不同類型的倒數元素;而後者則專門針對同類型的元素,提供更精確的選取能力。這兩個選擇器能夠滿足我們在排版中對元素的精細操作需求。