CSS - :first - child伪类
您可以使用 :first-child 伪类来选择元素的第一个子元素
注意:在IE8的之前版本必须声明<!DOCTYPE> ,这样 :first-child 才能生效。
匹配第一个 <p> 元素
在下面的例子中,选择器匹配作为任何元素的第一个子元素的 <p> 元素:
<html>
<head>
<style>
p:first-child
{
color:blue;
}
</style>
</head>
<body>
<p>I am a strong man.</p>
<p>I am a strong man.</p>
</body>
</html>
匹配所有<p> 元素中的第一个 <i> 元素
在下面的例子中,选择相匹配的所有<p>元素的第一 <i>元素:
<html>
<head>
<style>
p > i:first-child
{
color:blue;
}
</style>
</head>
<body>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
</body>
</html>
===
<html>
<head>
<style>
p:first-child i
{
color:blue;
}
</style>
</head>
<body>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
</body>
</html>
==
这个例子演示了如何使用 :focus伪类。
<style>
input:focus
{
background-color:yellow;
}
</style>
</head>
<body>
<form action="demo-form.php" method="get">
First name: <input type="text" name="fname" /><br>
Last name: <input type="text" name="lname" /><br>
<input type="submit" value="Submit" />
</form>
所有CSS伪类/元素
选择器 | 示例 | 示例说明 |
---|---|---|
:link | a:link | 选择所有未访问链接 |
:visited | a:visited | 选择所有访问过的链接 |
:active | a:active | 选择正在活动链接 |
:hover | a:hover | 把鼠标放在链接上的状态 |
:focus | input:focus | 选择元素输入后具有焦点 |
:first-letter | p:first-letter | 选择每个<p> 元素的第一个字母 |
:first-line | p:first-line | 选择每个<p> 元素的第一行 |
:first-child | p:first-child | 选择器匹配属于任意元素的第一个子元素的 <]p> 元素 |
:before | p:before | Insert content before every <p> element |
:after | p:after | 在每个<p>元素之前插入内容 |
:lang(language) | p:lang(it) | 为<p>元素的lang属性选择一个开始值 |