(CSS) Difference between :last-child and :last-of-type

Compare the descriptions of the pseudo-class selectors :last-child and :last-of-type in W3CSchool, as follows:

:last-child p:last-child Selects each <p> element that is the last child of its parent.
:last-of-type p:last-of-type Selects each <p> element that is the last <p> element of its parent.

To be honest, when I don’t understand the relationship between these two, the more I read these two descriptions, the more awkward, convoluted, and difficult to understand.

Take a piece of code as an example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>The difference between last-child and last-of-type</title>
    <style type="text/css">
        p:last-child{
            color: red;
        }

        p:last-of-type{
            color: blue;
        }

    </style>
</head>
<body>
    <div>
        <p>First line</p>
        <p>Second line</p>
        <p>The third line</p>
        <span>I am a test line</span>
    </div>
</body>
</html>

The result of the run shows: none of the rows are displayed in red, and the third row is displayed in blue. Maybe you may think that the two selectors select the same row, but when you comment out the blue selector, you will find that the red is still unselected.

In fact, the reason why red is not selected is very simple. I have already mentioned it in the previous article. Here is a brief description.

:last-child selects the last child node of the parent node and matches it with the selector. The last node of the parent node div is span, and the matching selector is p. The two do not correspond, so they do not match.

And another selector

:last-of-type is to find the last child node that is the same as the selector from the child nodes of the parent node, that is to say, this time it is not the last node, but the last P element node, so only Found the third line.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325332607&siteId=291194637