iT邦幫忙

2024 iThome 鐵人賽

DAY 18
1

nth-of-type

在先前的文章中,我們介紹了 :nth-child,它讓我們能根據所有同層元素的位置進行選取。而這次要介紹的 :nth-of-type,則是針對相同類型的元素進行篩選。

這意味著,如果有不同類型的元素混合在同一層中,:nth-of-type 只會對指定的元素類型生效,忽略其他類型的元素。例如,如果你要選取一個層級中的第三個 <div> 元素,其他類型的元素如 <p> 就不會干擾選取結果。
nth-of-type

💠:nth-of-type 基本用法

:nth-of-type 的使用方式與 :nth-child 幾乎相同。如果你了解 :nth-child 的語法,使用 :nth-of-type 也會輕而易舉。它會根據相同類型的兄弟元素來進行篩選。

語法

選擇器:nth-of-type(an+b) {
	屬性名: 屬性值;
}

選取同層同類型的元素中,符合 an+b 位置的元素:

  • a:元素的間隔數值,決定每隔幾個元素選一次
  • n:一個自然數,從 0 開始遞增 (0, 1, 2, 3...),代表每次計算的倍數
  • b:起始位置的偏移量,決定從哪個位置開始選取

範例

一起試試:[CODEPEN]

<div class="outer">
  <p class="box">p</p>
  <p class="box">p</p>
  <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 class="box">div</div>
  <div class="box">div</div>
  <div class="box">div</div>
  <div class="box">div</div>
  <div class="box">div</div>
  <div class="box">div</div>
  <div class="box">div</div>
  <div class="box">div</div>
</div>

1. 選中單個同類型元素

.outer div:nth-of-type(3) {
  background-color: gold;
}

選中 .outer 底下第三個為 <div> 的元素,這裡的 :nth-of-type(3) 等同於公式 0n + 3

nth-of-type

2. 選中偶數同類型元素

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

這會選取所有偶數位置的 <div> 元素,類似寫法還可以使用 even 關鍵字:

.outer div:nth-of-type(even) {
  background-color: gold;
}

nth-of-type

3. 選中奇數同類型元素

.outer div:nth-of-type(2n+1) {
  background-color: gold;
}

這樣會選中所有奇數位置的 <div> 元素,odd 關鍵字也能達到相同效果:

.outer div:nth-of-type(odd) {
  background-color: gold;
}

nth-of-type

4. 選中特定規則同類型元素

.outer div:nth-of-type(3n+2) {
  background-color: gold;
}

這將選擇 .outer 中的第 2、5、8、11... 等等位置的 <div> 元素,偏移量為 2,且每次間隔 3 個。

nth-of-type

隨堂小測驗

Q:如果要選中前五個 <div> 元素怎麼寫呢?

nth-of-type

A:

.outer div:nth-of-type(-n + 5) {
  background-color: gold;
}

-n+5 的意思是選擇前 5 個 <div> 元素。這種寫法的邏輯是通過使用負數範圍來逆向選取,也就是從第 1 個元素到第 5 個元素的範圍內都會被選中。


💠總結

:nth-of-type 是一個非常實用的選擇器,能幫助我們在相同類型的元素中依次篩選特定項目。無論是選中單個元素、偶數或奇數位置,還是根據複雜的規則進行篩選,:nth-of-type 提供了靈活的控制方式,特別是在處理含有不同類型混合的兄弟元素時,能夠精準地針對指定類型進行樣式設置。


上一篇
:first-of-type & :last-of-type 第一與最後的類型元素
下一篇
:nth-last-child & :nth-last-of-type 從後數起!CSS 的倒數計算法
系列文
你的優先選擇是什麼?從 CSS 選擇器到優先級,深入解析與實用技巧29
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言