:nth-of-type()

Baseline 已廣泛支援

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

:nth-of-type() CSS 偽類根據元素在其同類型(標籤名相同)兄弟元素中的位置來匹配元素。

試一試

dt {
  font-weight: bold;
}

dd {
  margin: 3px;
}

dd:nth-of-type(even) {
  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
:nth-of-type(<An+B> | even | odd) {
  /* ... */
}

引數

:nth-of-type() 偽類帶一個引數,該引數表示匹配元素的模式。

有關其語法的更詳細解釋,請參閱 :nth-child

示例

基本示例

HTML

html
<div>
  <div>This element isn't counted.</div>
  <p>1st paragraph.</p>
  <p class="fancy">2nd paragraph.</p>
  <div>This element isn't counted.</div>
  <p class="fancy">3rd paragraph.</p>
  <p>4th paragraph.</p>
</div>

CSS

css
/* Odd paragraphs */
p:nth-of-type(2n + 1) {
  color: red;
}

/* Even paragraphs */
p:nth-of-type(2n) {
  color: blue;
}

/* First paragraph */
p:nth-of-type(1) {
  font-weight: bold;
}

/* This will match the 3rd paragraph as it will match elements which are 2n+1 AND have a class of fancy.
The second paragraph has a class of fancy but is not matched as it is not :nth-of-type(2n+1) */
p.fancy:nth-of-type(2n + 1) {
  text-decoration: underline;
}

結果

注意:無法使用此選擇器選擇 nth-of-class。選擇器在建立匹配列表時只檢視型別。但是,您可以根據 :nth-of-type 的位置類來將 CSS 應用於元素,如上述示例所示。

規範

規範
選擇器 Level 4
# nth-of-type-pseudo

瀏覽器相容性

另見