:first-child
是CSS當中的一種偽類別(pseudo-class),代表任何身為長子的元素(親元素的第一個子元素)。
語法
:first-child
範例
範例 1
HTML 內文
<div>
<span>This span is limed!</span>
<span>This span is not. :(</span>
</div>
CSS 內文
span:first-child {
background-color: lime;
}
呈現效果如下:
範例 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;
}
呈現效果如下:
規格
規格 | 狀態 | 註解 |
---|---|---|
Selectors Level 4 The definition of ':first-child' in that specification. |
Working Draft | 無變更 |
Selectors Level 3 The definition of ':first-child' in that specification. |
Recommendation | 無變更 |
CSS Level 2 (Revision 1) The definition of ':first-child' in that specification. |
Recommendation | 初始定義 |
瀏覽器相容性
We're converting our compatibility data into a machine-readable JSON format.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
Find out how you can help!
功能 | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
基礎支援 | 4.0 | 3.0 (1.9) | 7[1] | 9.5 | 4 |
功能 | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
基礎支援 | 1.0 | 1.0 (1.9.1) | 7[1] | 10.0 | 3.1 |
[1] 在不重新載入網頁的情況下,Internet Explorer 7 的樣式表並不會套用在動態新增的元素上。在 Internet Explorer 8,若元素是以點擊連結而形成的,則 first-child
在該連結不被選取後才有作用。