5

CSS3 选择器 :nth-child 与 :nth-of-type 区别

 2 years ago
source link: https://segmentfault.com/a/1190000040896695
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、:nth-child

1.1 说明

:nth-child(n) 选择器匹配属于其父元素的第 N 个子元素,不论元素的类型。n 可以是数字、关键词或公式。

注意:如果第 N 个子元素与选择的元素类型不同则样式无效!

1.2 示例

<style>
div>p:nth-child(2){
    color:red;
}
</style>
<div>
    <p>我是第1个段落</p>
    <p>我是第2个段落</p><!--符合条件:1、是<p>元素,2、父元素<div>的第二个元素。这里被选择,会变成红色。-->
    <p>我是第3个段落</p>
</div>
<div>
    <p>我是第1个段落</p>
    <span>我是第1个文本</span><!--不符合条件:不是<p>元素,没有被选择-->
    <p>我是第2个段落</p>
</div>

二、:nth-of-type

2.1 说明

:nth-of-type(n) 选择器匹配属于父元素的特定类型的第 N 个子元素的每个元素。n 可以是数字、关键词或公式。

2.2 示例

<style>
div>p:nth-of-type(2){
    color:red;
}
</style>
<div>
    <p>我是第1个段落</p>
    <p>我是第2个段落</p><!--符合条件:1、是特定元素类型<p>,2、是父元素<div>的第二个<p>元素。这里被选择,会变成红色-->
    <p>我是第3个段落</p>
</div>
<div>
    <p>我是第1个段落</p>
    <blockquote>第1个引用</blockquote>
    <p>我是第2个段落</p><!--符合条件:1、是特定元素类型<p>,2、是父元素<div>的第二个<p>元素。这里被选择,会变成红色-->
    <p>我是第3个段落</p>
</div>

版权声明

本博客所有的原创文章,作者皆保留版权。转载必须包含本声明,保持本文完整,并以超链接形式注明作者后除和本文原始地址:https://blog.mazey.net/431.html


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK