David Lougheed
David Lougheed

Reputation: 79

Last-child selector only works when no div follows

I'm working on a project which involves messages that appear at the top. However, last-child doesn't seem to work when trying to select the last error message shown. You can see this here: http://jsfiddle.net/XNVCz/

However, when I take away the small bit of code at the end of the HTML;

<div class="container"></div>

Then last-child works again even though that div is not of the same class. What am I doing wrong?

Upvotes: 0

Views: 135

Answers (3)

David Thomas
David Thomas

Reputation: 253318

:last-child as the name implies selects the last child of its parent (if it also matches the previous, element-name, part of the selector.

It does not, however, acknowledge class-names; therefore your selector .messager:last-child is looking to match only the :last-child of the parent.

And, clearly, when you insert another element as the last-child of the common parent, the other element is no longer the last-child of that parent. And, as yet, there is no :last-of-class selector, sadly.

Upvotes: 1

Milche Patern
Milche Patern

Reputation: 20452

You need to put your <div class="message"> in a parent divider in order to scope them with ':last-child'.

jsfiddle.net/XNVCz/1/

<div>
    <div class="messager err">
        <div> <strong>Error:</strong> You did not enter the verification code properly.
            <a class="closemessage"><span aria-hidden="true" class="icon-x"></span></a>
        </div>
    </div>
    <div class="messager err">
        <div> <strong>Error:</strong> You did not enter the verification code properly.
            <a class="closemessage"><span aria-hidden="true" class="icon-x"></span></a>
        </div>
    </div>
</div>

Upvotes: 0

Zoltan Toth
Zoltan Toth

Reputation: 47667

The :last-child selector is unaware of classes.

It selects the element if it's "the last child element of its parent element" ( reference ) regardless of classes, id-s etc.

Upvotes: 1

Related Questions