CSS 伪类选择器 :first-child() 和 :first-of-type()

CSS About 1,156 words

:first-child()

表示在一组兄弟元素中的第一个元素。

语法

:first-child {
  /* ... */
}

示例

只有第一个<li>1</li>border样式。

li:first-child {
  border: 2px solid orange;
}

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

:first-of-type()

表示一组兄弟元素中其类型的第一个元素。

语法

:first-of-type {
  /* ... */
}

示例一

<p>Paragraph 1</p>将应用样式。

p:first-of-type {
  color: red;
  font-style: italic;
}

<h2>Heading</h2>
<p>Paragraph 1</p>
<p>Paragraph 1</p>

示例二

article下同级元素中第一次出现的相同元素将应用样式(不同元素第一次出现也将应用样式)。

以下元素都应用了样式。

  • <div>This div is first!</div>
  • <span>nested span is first</span>
  • <em>nested em is first</em>
  • <span>nested span gets styled</span>
  • <p>This p qualifies!</p>
article :first-of-type {
  background-color: pink;
}

<article>
  <div>This `div` is first!</div>
  <div>This <span>nested `span` is first</span>!</div>
  <div>
    This <em>nested `em` is first</em>, but this <em>nested `em` is last</em>!
  </div>
  <div>This <span>nested `span` gets styled</span>!</div>
  <p>This `p` qualifies!</p>
  <div>This is the final `div`.</div>
</article>

参考文档

https://developer.mozilla.org/zh-CN/docs/Web/CSS/:first-child

https://developer.mozilla.org/zh-CN/docs/Web/CSS/:first-of-type

Views: 23 · Posted: 2025-11-11

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Today In History
Browsing Refresh