--- title: ':first-child' slug: 'Web/CSS/:first-child' tags: - CSS - CSS Pseudo-class - Layout - Reference - Web translation_of: 'Web/CSS/:first-child' ---
{{CSSRef}}

:first-childCSS當中的一種偽類別(pseudo-class),代表任何身為長子的元素(親元素的第一個子元素)。

語法

{{csssyntax}}

範例

範例 1

HTML 內文

<div>
  <span>This span is limed!</span>
  <span>This span is not. :(</span>
</div>

CSS 內文

span:first-child {
    background-color: lime;
}

呈現效果如下:

{{EmbedLiveSample('範例_1',300,50)}}

範例 2 - 使用 UL

HTML 內文

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

CSS 內文

li{
  color:red;
}
li:first-child{
  color:green;
}

呈現效果如下:

{{EmbedLiveSample('範例_2_-_使用_UL',300,100)}}

規格

規格 狀態 註解
{{SpecName('CSS4 Selectors', '#first-child-pseudo', ':first-child')}} {{Spec2('CSS4 Selectors')}} 無變更
{{SpecName('CSS3 Selectors', '#first-child-pseudo', ':first-child')}} {{Spec2('CSS3 Selectors')}} 無變更
{{SpecName('CSS2.1', 'selector.html#first-child', ':first-child')}} {{Spec2('CSS2.1')}} 初始定義

瀏覽器相容性

{{CompatibilityTable}}

功能 Chrome Firefox (Gecko) Internet Explorer Opera Safari
基礎支援 4.0 {{CompatGeckoDesktop("1.9")}} 7[1] 9.5 4
功能 Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
基礎支援 1.0 {{CompatGeckoMobile("1.9.1")}} 7[1] 10.0 3.1

[1] 在不重新載入網頁的情況下,Internet Explorer 7 的樣式表並不會套用在動態新增的元素上。在 Internet Explorer 8,若元素是以點擊連結而形成的,則 first-child 在該連結不被選取後才有作用。

參見