:last-child 和 :last-of-type

作为CSS常用伪类选择器,:last-child经常会被用到;

但有时遇到极端情况,它会意外失效,让人摸不着头脑,例子如下:
html:

<div class="card">
        <p>1</p>
        <p>2</p>
        <p>3</p>
        <p>4</p>
        <p>5</p>
        <p>6</p>
        <p>7</p>
        <span>next is ...</span>
    </div>

css:

.card {
    color: white;
    > p {
        &:last-child {
            border: 5px solid pink;
        }
    }
}

结果:

 看到是不生效的,但是使用:last-of-type确实生效的

1.:last-child选取一群兄弟元素中的最后一个元素,且最后的这个元素必须是所声明的指定元素(注意2个条件);

(本文例子中,不生效是最后的这个元素不是所声明的指定元素)

2.:last-of-type选取一群兄弟元素中的最后一个指定类型的元素。

可知,:last-of-type更严谨一些,不容易产生意外bug,我更推荐使用它。同理适用于:nth-last-child(n):nth-last-of-type(n)

原文地址:https://www.cnblogs.com/ssszjh/p/14557047.html