另一个静态伪类:first-child来选择元素的第一个子元素。这个特定伪类很容易遭到误解,所以有必要举个例子来说明。考虑以下标记:
<div>
<p>These are the necessary steps:</p>
<ul>
<li>Insert key</li>
<li>Turn key <strong>clockwise</strong></li>
<li>Push accelerator</li>
</ul>
<p> Do <em>not</em> push the brake at the same time as the accelerator.
</p>
<div>
在这个例子中,作为第一个子元素的元素包括第一个p、第一个li和strong及em元素。给定以下两个规则:
p:first-child {font-weight: bold;}
li:first-child {text-transform: uppercase;}
前一个规则将作为某元素第一个子元素的所有P元素设置为粗体。第二个规则将作为某个元素(在制作网页HTML中,这肯定是一个ol或ul元素)第一个子元素的所有li元素变成大写。
最常见的错误是认为p:first-child之类的选择器会选择p元素的第一个子元素。不过,要记住伪类的实质,它是把某种幻像类关联到与伪类相关的元素。如果要向标记增加具体类,可能如下所示:
<div>
<p class="first-child">These are the necessary steps:</p>
<li class="first-child">Insert key</li>
<li>Turn key <strong class='first-child">clockwise</strongx/li>
<li>Push accelerator</li>
</ul>
<p> Do <em class="first-child">not</em> push the brake at the same time as the accelerator.
</p>
</div>
因此,如果想选择作为某元素第一个子元素的em元素,应当写作em:first-child。这个选择器才能真正达到你的目的,例如,对列表中的第一项、div中的第一段或表行中的第一个td应用样式。
警告:windows平台的Internet Explorer在IE6之前不支持:first-child,不过IE7支持。