:first-child CSS伪类 代表了一组兄弟元素中的第一个元素。在level3实现中,被匹配的元素需要具有一个父级元素,而在level4实现中则不需要。

语法

:first-child
element:first-child { style properties }

示例

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

上面的CSS作用于下面的HTML:

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

就会显示出这样的效果:
This span is limed! This span is not. :(

 

例子2 - 使用UL

HTML Content

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

CSS Content

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

... 看起来像 ...

规范

Specification Status Comment
Selectors Level 4
:first-child
Working Draft No change.
Selectors Level 3
:first-child
Recommendation Initial definition.

浏览器兼容性

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!

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 4.0 3.0 (1.9) 7 9.5 4
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 1.0 1.0 (1.9.1) 7 10.0 3.1

IE附注

Internet Explorer 7 doesn't update the styles when elements are added dynamically. In Internet Explorer 8, if an element is inserted dynamically by clicking on a link the first-child style isn't applied until the link loses focus.

 

See also

文档标签和贡献者

 此页面的贡献者: silhouettesia, xgqfrms-GitHub, FredWe, teoli, ziyunfei
 最后编辑者: silhouettesia,