CSS3 :nth-child() 选择器
指定每个p元素匹配父元素中的第2个子元素的背景色:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
p:nth-child(2) {
background: #ff0000;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
<p><b>注意:</b> Internet Explorer 8 以及更早版本的浏览器不支持 :nth-child()选择器.</p>
</body>
</html>
定义和用法
:nth-child(n)选择器匹配父元素中的第n个子元素。
n可以是一个数字,一个关键字,或者一个公式。
提示: 请参阅选择器。该选择器匹配同类型中的第n个同级兄弟元素。
浏览器支持
表格中的数字表示支持该属性的第一个浏览器版本号。
选择器 | |||||
---|---|---|---|---|---|
:nth-child() | 4.0 | 9.0 | 3.5 | 3.2 | 9.6 |
更多实例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
p:nth-child(odd) {
background: #ff0000;
}
p:nth-child(even) {
background: #0000ff;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p><b>注意:</b> Internet Explorer 8 and以及更早版本的浏览器 :nth-child()选择器.</p>
</body>
</html>
使用公式(an+ b).描述:a代表一个循环的大小,N是一个计数器(从0开始),以及b是偏移量。 在这里,我们对所有索引是3的倍数的p元素指定了背景颜色:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
p:nth-child(3n+0) {
background: #ff0000;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
<p>The fifth paragraph.</p>
<p>The sixth paragraph.</p>
<p>The seventh paragraph.</p>
<p>The eight paragraph.</p>
<p>The ninth paragraph.</p>
<p><b>注意:</b> Internet Explorer 8以及更早版本的浏览器不支持:nth-child()选择器.</p>
</body>
</html>