CSS :first-child 选择器
匹配属于父元素中第一个子元素的每个<p>元素
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
p:first-child {
background-color: yellow;
}
</style>
</head>
<body>
<p>This paragraph is the first child of its parent (body).</p>
<h1>Welcome to My Homepage</h1>
<p>This paragraph is not the first child of its parent.</p>
<div>
<p>This paragraph is the first child of its parent (div).</p>
<p>This paragraph is not the first child of its parent.</p>
</div>
<p><b>注意:</b> :first-child作用于 IE8以及更早版本的浏览器, DOCTYPE必须已经声明.</p>
</body>
</html>
定义和用法
:only-child选择器匹配属于父元素中唯一子元素的元素。
浏览器支持
表格中的数字表示支持该属性的第一个浏览器版本号。
选择器 | |||||
---|---|---|---|---|---|
:first-child | 4.0 | 7.0 | 3.0 | 3.1 | 9.6 |
注意: :first-child在IE8和更早版本IE版本中必须声明<!DOCTYPE>
相关文章
CSS 教程: CSS 伪类
更多实例
<p>元素是其父级的第一个子元素,每个<p>元素的 <i>元素的样式:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
p:first-child i {
background: yellow;
}
</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>
<p><b>注意:</b> :first-child作用于 IE8以及更早版本的浏览器, DOCTYPE必须已经声明.</p>
</body>
</html>
列表中的第一个 <li>元素选择的样式:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
li:first-child {
background: yellow;
}
</style>
</head>
<body>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
<p><b>注意:</b> :first-child作用于IE8以及更早版本的浏览器, DOCTYPE必须已经声明</p>
</body>
</html>
每一个<ul>元素的第一个子元素选择的样式::
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
ul>:first-child {
background: yellow;
}
</style>
</head>
<body>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
<p><b>注意:</b> :first-child作用于 IE8以及更早版本的浏览器, DOCTYPE必须已经声明.</p>
</body>
</html>