:nth-of-type()
试一试
语法
nth-of-type
伪类使用单个参数指定,该参数表示匹配元素的模式。
有关其语法的更详细解释,请参阅 :nth-child
。
css
:nth-of-type(<An+B> | even | odd) {
/* ... */
}
示例
基本示例
HTML
html
<div>
<div>This element isn't counted.</div>
<p>1st paragraph.</p>
<p class="fancy">2nd paragraph.</p>
<div>This element isn't counted.</div>
<p class="fancy">3rd paragraph.</p>
<p>4th paragraph.</p>
</div>
CSS
css
/* Odd paragraphs */
p:nth-of-type(2n + 1) {
color: red;
}
/* Even paragraphs */
p:nth-of-type(2n) {
color: blue;
}
/* First paragraph */
p:nth-of-type(1) {
font-weight: bold;
}
/* This will match the 3rd paragraph as it will match elements which are 2n+1 AND have a class of fancy.
The second paragraph has a class of fancy but is not matched as it is not :nth-of-type(2n+1) */
p.fancy:nth-of-type(2n + 1) {
text-decoration: underline;
}
结果
**注意:** 此选择器无法选择第 n 个类。选择器在创建匹配列表时只查看类型。但是,您可以根据 :nth-of-type
位置和类来应用 CSS,如上面的示例所示。
规范
规范 |
---|
选择器级别 4 # nth-of-type-pseudo |
浏览器兼容性
BCD 表格仅在浏览器中加载