Question

<!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?

Was it helpful?

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.

OTHER TIPS

Since the :last-child selector selects all elements that are the last child of their parent.

By default all elements selected it, the first one is to specify the p element. [Google Translation]

p:last-child works by applying the CSS property to only the last child of a paragraph element.

:last-child works by applying the CSS property to the last child of the parent element. In this case, the last child would always be the body, since we always have one body, right? :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top