only-child、only-of-type、nth-child、 nth-of-type

本文详细解释了CSS中的四个选择器:only-child、only-of-type、nth-child及其变体,包括它们的选取条件和应用场景。only-child选择器用于选取父元素下的唯一子元素;only-of-type则关注同类型的唯一元素。nth-child(n)选取父元素下的第n个子元素,而nth-last-child(n)则是从后向前计数。last-of-type和first-child分别对应最后和第一个指定类型的元素。同样,nth-of-type(n)和nth-last-of-type(n)针对的是指定类型的元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先从最不容易理解的only-child,only-of-type说起吧,理解这两个后面的都好理解了。

1. only-child

选取条件:需要有父元素(不包含body元素),父元素下只有一个元素,且该唯一个元素为指定元素。

a:only-child{
color:blue;
}
<body>
<div>
  <div>
 	 <a>a标签1</a>
  </div>
</div>

<div>
  <div>
    <a>a标签2</a> // 不满足“父元素下只有一个元素”条件
    <p>p标签</p>
  </div>
</div>

<div>
  <div>
    <a>a标签3</a> // 不满足“唯一个元素为指定元素”条件
    <a>a标签4</a> // 同上
  </div>
</div>

<a>a标签5</a>  // 不满足“有父元素(不包含body元素)”条件
</body>

在这里插入图片描述

2. only-of-type

选取条件:有父元素(包含body元素),指定元素在父元素中唯一。

a:only-of-type{
color:blue;
}
<body>
<div>
  <div>
 	 <a>a标签1</a>
  </div>
</div>
<div>
  <div>
    <a>a标签2</a>
    <p>p标签</p>
  </div>
</div>

<div>
  <div>
    <a>a标签3</a> // 不满足"指定元素在父元素中唯一"条件
    <a>a标签4</a>  // 同上
  </div>
</div>

<a>a标签5</a>
</body>

在这里插入图片描述

3. nth-child

选取条件:选取在每一个具有子元素的元素(包含body元素)中,指定位置为指定元素的元素。注意:指定位置是指第几个child,无论是什么元素。

a:nth-child(2){
color:blue;
}
<body>

<div>
  <div>
    <a>a标签1</a> // 不是指定位置2,是该div的第1个child
    <a>a标签2</a>
  </div>
  
  <div>
    <a>a标签3</a>  // 不是指定位置2,是该div的第1个child
    <p>p标签</p>  // 不是指定元素a
  </div>
</div>

<a>a标签4</a>
<a>a标签5</a>  // 不是指定位置2,是body的第3个child

</body>

![在这里插入图片描述](https://img-blog.csdnimg.cn/20210316165231799.png

nth-last-child()

和nth-child()相似,只不过指定位置是和nth-child()相反,也就是从后往前计数。

last-of-type

相当于nth-last-of-type(1).

first-child

相当于nth-child(1).
在这里插入图片描述

4. nth-of-type

选取条件:选取在每一个具有子元素的元素(包含body元素)中,指定位置为指定元素的元素。注意:指定位置是指第几个指定元素。

a:nth-of-type(2){
color:blue;
}
<body>

<div>
  <div>
    <a>a标签1</a>  // 不是指定位置2,是该div的第1个a
    <a>a标签2</a>
  </div>
  
  <div>
    <p>p标签</p>
    <a>a标签3</a> // 不是指定位置2,是该div的第1个a
  </div>
</div>

<a>a标签4</a>  // 不是指定位置2,是body的第1个a
<a>a标签5</a>

</body>

在这里插入图片描述

nth-last-of-type()

和nth-of-type()相似,只不过指定位置是和nth-of-type()相反,也就是从后往前计数。

last-of-type

相当于nth-last-of-type(1).

first-of-type

相当于nth-of-type(1).

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值