CSS :nth-last-of-type(n)选择器,倒序匹配特定元素

:nth-last-of-type(n)选择器

CSS伪类选择器:nth-last-of-type(n)选择器可匹配获取某一特定元素的父元素的倒数第n个该类型的子元素。如果觉得这句话理解比较费劲,可参考下方的语法部分的内容。


语法及参数

E:nth-last-of-type(n){样式设置}

提示:该伪类选择器匹配选择元素的步骤(个人理解,仅供参考):1、将通过E选择器匹配选择到的元素的父元素下的该类型的子元素构成一个“元素集合”,2、通过参数n的指定,匹配选择该集合中倒数第n个该类型的子元素。


参数解析表:

n的值描述
数字指定E元素的父元素下的E元素集合中倒序第n个元素被匹配。
odd或evenodd匹配倒序为奇数的E类型元素;even匹配倒序为偶数的E类型元素。
公式如2n匹配倒序为2的倍数的子元素。

:nth-last-of-type(n)选择器实例代码,及在线编辑器

n为数字的实例:

<div>
  <h6>倒序为2的h6</h6>
  <p class='e1'>div的p类子元素倒序为3的元素</p>
  <p class='e1'>倒序为2的p元素</p>
  <p class='e1'>倒序为3的p元素</p>
  <h6>倒序为1的h6</h6>
</div>
<style>
  .e1:nth-last-of-type(1){color:blue;}
  h6:nth-last-of-type(2){color:skyblue;}
</style>

n为关键字的实例

<div>
  <h6>1h6</h6>
  <p class='e2'>1</p>
  <p class='e2'>2</p>
  <p class='e2'>3</p>
  <h6>2h6</h6>
</div>
<style>
  .e2:nth-last-of-type(odd){color:blue;}
  .e2:nth-last-of-type(even){color:orange;}
  h6:nth-last-of-type(odd){color:skyblue;}
  h6:nth-last-of-type(even){color:pink;}
</style>

n为公式的实例

<div>
  <h6>壹</h6>
  <p class='e3'>段落(1)</p>
  <p class='e3'>段落(2)</p>
  <p class='e3'>段落(3)</p>
  <h6>贰</h6>
</div>
<style>
  .e3:nth-last-of-type(2n+1){color:blue;}
  h6:nth-last-of-type(2n){color:skyblue;}
</style>

全栈前端 / CSS教程 :



























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.