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


工作中老用到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.

最基本的演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!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标签,像下面这个样就不行了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!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标签。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!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标签:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!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)