CSS3 :nth-of-type() Selector | CSS 伪类(Pseudo-classes) | CSS教程

返回到:CSS 伪类(Pseudo-classes) | CSS教程

定义和用法

:nth-of-type(n)选择器匹配同类型中的第n个同级兄弟元素。

n可以是一个数字,一个关键字,或者一个公式。

提示: 请参阅 :nth-child() 选择器。该选择器匹配父元素中的第n个子元素。

浏览器支持

表格中的数字表示支持该属性的第一个浏览器版本号。

选择器谷歌IE火狐苹果opera
:nth-of-type(n)4.09.03.53.29.6

实例

指定每个p元素匹配同类型中的第2个同级兄弟元素的背景色:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>Web176教程(web176.com)</title> 
<style> 
p:nth-of-type(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>

</body>
</html>

奇数和偶数是可以作为关键字使用用于相匹配的子元素,其索引是奇数或偶数(该索引的第一个子节点是1)。

在这里,我们为奇数和偶数p元素指定两个不同的背景颜色:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>Web176教程(web176.com)</title> 
<style> 
p:nth-of-type(odd)
{
	background:#ff0000;
}
p:nth-of-type(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>

</body>
</html>

使用公式(an+ b).描述:a代表一个循环的大小,N是一个计数器(从0开始),以及b是偏移量。

在这里,我们对所有索引是3的倍数的p元素指定了背景颜色:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>Web176教程(web176.com)</title> 
<style> 
p:nth-of-type(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>

</body>
</html>

作者:terry,如若转载,请注明出处:https://www.web176.com/cssprop/5381.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2022年4月8日 下午5:16
下一篇 2022年4月8日 下午5:27

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注