last-child到底怎么用

last-child 

last-of-type

这两个容易弄混,看一下官网对last-of-type的定义:

https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type

再看last-child:

 https://developer.mozilla.org/en-US/docs/Web/CSS/:last-child

一个是last element of its type among siblings 一个是 last element among siblings

这里的type 指的应该是元素的类型

===============================================================================

<div>

<p>1</p>

<p>2</p>

<p>3</p>

<span>哈比</span>

</div>

p:last-child是选择不到的,这是为什么呢?

el:last-child 的匹配规则是:第一步,查找 el 选择器匹配元素的所有同级元素(siblings);第二步,在同级元素中查找最后一个元素;第三步,检验最后一个元素是否与选择器 el 匹配。


总结: :last-child表示其父元素的最后一个子元素,且这个元素是css指定的元素,才可以生效。

顺便提一下 :last-of-type 这个伪类,在这里是可以用的。

el:last-of-type的匹配规则是:查找 el 选择器匹配元素的所有同级元素(siblings),查找和el同type的元素中的最后一个元素(type指的是元素类型),检验最后一个元素类型是否与选贼器el匹配

但是last-of-type的规则也是要注意的,如果遇到这种情况:

<div>
<div class='a'>
1
</div>
<div class='a'>
2
</div>

<div class='a'>
3
</div>

<div class='b'>
4
</div>
</div>


我选写 .a:last-of-type 也是选择不到的,因为这个东东匹配的是元素类型,最后一个元素的类型也是div,所以并不行。

原文地址:https://www.cnblogs.com/eret9616/p/9445158.html