nth-last-child()和nth-last-of-type() 的区别、以及选择则倒数几个元素

1 篇文章 0 订阅

 工作中老用到css选择器对nth-last-child()和nth-last-of-type()用法不是熟练,今天整理下。

最开始看的w3c的中文文档,看的有点蒙,后来发现可能是翻译问题。。。

先说结论:nth-last-of-type()只匹配指定的标签类型,nth-last-child()不管标签类型

举例:

1、nth-last-child()

The :nth-last-child(n) selector matches every element that is the nth child, regardless of type, of its parent, counting from the last child. 

最基本的演示:

<!DOCTYPE html>
<html>
<head>
<style> 
p:nth-last-child(2)
{
background:#ff0000;
}
</style>
</head>
<body>
<h1>这是标题</h1>
<p>第一个段落。</p>
<p>第二个段落。</p>
<h6>第三个段落。</h6>
</body>
</html>

效果:

 匹配到的p标签的父元素使body标签,body子元素的倒数第二个标签就是第二个段落,虽然倒数第一个子元素不是p标签是h1标签,但是nth-last-child()不管标签类型。

但是要选中目标标签一定要是p标签,像下面这个样就不行了

<!DOCTYPE html>
<html>
<head>
<style> 
p:nth-last-child(2)
{
background:#ff0000;
}
</style>
</head>
<body>
<h1>这是标题</h1>
<p>第一个段落。</p>
<h6>第二个段落。</h6>
<p>第三个段落。</p>
</body>
</html>

因为匹配到的元素是h6标签,所以不会变色。

2、nth-last-of-type()

The :nth-last-of-type(n) selector matches every element that is the nth child, of a particular type, of its parent, counting from the last child.

<!DOCTYPE html>
<html>
<head>
<style> 
p:nth-last-of-type(2)
{
background:#ff0000;
}
</style>
</head>
<body>
<h1>这是标题</h1>
<p>第一个段落。</p>
<p>第二个段落。</p>
<p>第三个段落。</p>
</body>
</html>

 效果

也成功同样将倒数第二个p标签也就是第二个段落变色。

改一下,将第三个段落改为h6标签。

<!DOCTYPE html>
<html>
<head>
<style> 
p:nth-last-of-type(2)
{
background:#ff0000;
}
</style>
</head>
<body>
<h1>这是标题</h1>
<p>第一个段落。</p>
<p>第二个段落。</p>
<h6>第三个段落。</h6>
</body>
</html>

效果:

这回将第一个段落变色了。

因为 nth-last-of-type必须要匹配标签类型,所以只计算p标签,忽略了h6标签,那倒数第二个p标签自然就是段落一了。


选择倒数后两个p标签:

p:nth-last-of-type(-n+2)

<!DOCTYPE html>
<html>
<head>
<style> 
p:nth-last-of-type(-n+2)
{
background:#ff0000;
}
</style>
</head>
<body>
<h1>这是标题</h1>
<p>第一个段落。</p>
<p>第二个段落。</p>
<p>第三个段落。</p>

</body>
</html>

选择前两个p标签:

<!DOCTYPE html>
<html>
<head>
<style> 
p:nth-last-of-type(n+2)
{
background:#ff0000;
}
</style>
</head>
<body>
<h1>这是标题</h1>
<p>第一个段落。</p>
<p>第二个段落。</p>
<p>第三个段落。</p>

</body>
</html>

p:nth-last-of-type(n+2)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值