Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. CSS:层叠样式表
  3. CSS 参考
  4. 选择器
  5. :nth-of-type

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

:nth-of-type

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since 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>

语法

nth-of-type 伪类用单个参数指定,该参数表示匹配元素的模式。

有关其语法的详细说明,请参阅:nth-child

css
:nth-of-type(<an-plus-b> | even | odd) {  /* ... */}

示例

基本示例

HTML

html
<div>  <div>这段不参与计数。</div>  <p>这是第一段。</p>  <p>这是第二段。</p>  <div>这段不参与计数。</div>  <p>这是第三段。</p>  <p>这是第四段。</p></div>

CSS

css
/* 奇数段 */p:nth-of-type(2n + 1) {  color: red;}/* 偶数段 */p:nth-of-type(2n) {  color: blue;}/* 第一段 */p:nth-of-type(1) {  font-weight: bold;}/* 这将匹配第三个段落,因为它匹配的元素是 2n+1 并且具有 fancy 类。   第二个段落具有 fancy 类,但不匹配,因为它不是:nth-of-type(2n+1)。*/p.fancy:nth-of-type(2n + 1) {  text-decoration: underline;}

结果

备注:使用此选择器无法选择 nth-of-class。选择器仅在创建匹配列表时查找类型。但是你可以基于:nth-of-type 的位置类名为元素应用 CSS,就像上面的示例中所示。

规范

Specification
Selectors Level 4
# nth-of-type-pseudo

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp