nth-of-type() 详解

nth-of-type() 详解

ele:nth-of-type(n)表示选择父元素下的第 nele 元素,其中 n 可以是正整数、公式或者关键字。同时, ele 一般是标签选择器。

<style>
  * {
    margin: 0;
    padding: 0;
  }
  .box {
    width: 400px;
    height: 200px;
    margin: 100px auto;
    border: 1px solid #ccc;
  }
  li {
    padding-left: 16px;
    list-style: none;
  }
</style>

<div class="box">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
  </ul>
</div>

nth-01.png

1. n 作为正整数、

n 作为一个具体的数时,从 1 开始生效。

<style>
  /* .... */
  li:nth-of-type(1), li:nth-of-type(4) {
    background-color: #eee;
    color: #1890ff;
  }
</style>

nth-02.png

2. n 作为关键字

even | odd,选择偶数还是奇数。

<style>
  /* .... */
  li:nth-of-type(even) {
    background-color: #eee;
    color: #1890ff;
  }
</style>

nth-03.png

3. n 作为公式

作为公式时, n 是从 0 开始的。

<style>
  /* .... */
  li:nth-of-type(n+2):nth-of-type(-n+4) {
  background-color: #eee;
  color: #1890ff;
}
</style>

nth-04.png

上面组合使用的,表示从第二行到第四行,闭区间。

也可以将其拆开使用, li:nth-of-type(n+2) 表示从第二行到最末尾,li:nth-of-type(-n+4) 表示从开始到第四行。

4. 作用范围:

ele:nth-of-type() 作用的是父元素下第几个 ele 元素,如果中间有其他元素,则略过。

<style>
  * {
    margin: 0;
    padding: 0;
  }
  .box {
    width: 400px;
    height: 200px;
    margin: 100px auto;
    border: 1px solid #ccc;
  }
  p:nth-of-type(3) {
    background-color: #eee;
    color: #1890ff;
  }
</style>
<div class="box">
  <p>1</p>
  <p>2</p>
  <div>3-div</div>
  <p>4</p>
  <p>5</p>
</div>

nth-05.png

nth-child和nth-of-typeCSS的两个伪选择符,用于选择特定位置的元素。 nth-child(n)选择的是在其父元素下的第n个子元素,无论其类型是什么。例如,如果我们使用nth-child(2)选择器,它会选择父元素下的第二个子元素,无论其类型是什么。 而nth-of-type(n)选择的是在其父元素下,与其同类型的第n个子元素。也就是说,它只会选择与给定类型相同的元素。例如,如果我们使用nth-of-type(2)选择器,它只会选择父元素下同类型的第二个子元素。 因此,nth-child和nth-of-type之间的区别在于选择的元素类型不同。nth-child不考虑元素的类型,而nth-of-type只考虑与给定类型相同的元素。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [CSS3nth-of-typenth-child区别分析详解nth-of-typenth-child对比区别,CSS3强大选择器nth-of-type...](https://blog.youkuaiyun.com/MFWSCQ/article/details/89150093)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *3* [详解CSS nth-child与nth-of-type的元素查找方式](https://download.youkuaiyun.com/download/weixin_38592256/14831190)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值