: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

浏览器兼容性

另见