CSS2 - :first-child 伪类
您可以使用 :first-child 伪类来选择元素的第一个子元素。这个特定伪类很容易遭到误解,所以有必要举例来说明。考虑以下标记:
These are the necessary steps:
- Intert Key
- Turn key clockwise
- Push accelerator
Do not push the brake at the same time as the accelerator.
在上面的例子中,作为第一个元素的元素包括第一个 p、第一个 li 和 strong 和 em 元素。
给定以下规则:
p:first-child {font-weight: bold;}
li:first-child {text-transform:uppercase;}
第一个规则将作为某元素第一个子元素的所有 p 元素设置为粗体。第二个规则将作为某个元素(在 HTML 中,这肯定是 ol 或 ul 元素)第一个子元素的所有 li 元素变成大写。
请访问该链接,来查看这个 :first-child 实例的效果。
提示:最常见的错误是认为 p:first-child 之类的选择器会选择 p 元素的第一个子元素。
注释:必须声明 ,这样 :first-child 才能在 IE 中生效。
为了使您更透彻地理解 :first-child 伪类,我们另外提供了 3 个例子:
例子 1 - 匹配第一个
元素
在下面的例子中,选择器匹配作为任何元素的第一个子元素的 p 元素:
p:first-child {
color: red;
}
some text
some text
例子 2 - 匹配所有
元素中的第一个 元素
在下面的例子中,选择器匹配所有
元素中的第一个 元素:
p > i:first-child {
font-weight:bold;
}
some text. some text.
some text. some text.
例子 3 - 匹配所有作为第一个子元素的
元素中的所有 元素
在下面的例子中,选择器匹配所有作为元素的第一个子元素的
元素中的所有 元素:
p:first-child i {
color:blue;
}
some text. some text.
some text. some text.