Search code examples
csscss-selectorspseudo-class

css: issue with :last-child selector


<!DOCTYPE html>
<html>
<head>
<style> 
p:last-child
{
background:#ff0000;
}
</style>
</head>
<body>

<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>

</body>
</html>

Question:

If i change

p:last-child
    {
    background:#ff0000;
    }

to

:last-child
        {
        background:#ff0000;
        }

then the whole page became red. why? what is the difference between p:last-child and :last-child?


Solution

  • p:last-child will select a p element if it's a last-child, if you've any other element as your last-child it will fail

    Demo

    In this case, you should use a more stricter pseudo like

    p:last-of-type {
       background:#ff0000;
    }
    

    Demo 2

    The above will select p element, which is last regardless of any other element which can be last-child of the parent element.


    Coming to this selector, :last-child, is not specific at all, you haven't specified last-child of what? So it will select any parent elements last-child

    So

    :last-child {
        background:#ff0000;
    }
    

    Will select i and body element but NOT p as it's not the last-child of body, same way if you use :last-of-type it will select

    i body as well as p because now we are using last-of-type so it selects last element of each distinct element.

    Demo


    You can use firebug to inspect each element and see how the elements pick up these properties.