Search code examples
csspseudo-classcss-selectors

:first-child fails when an element of a different class is dynamically inserted above


So, I've encountered a situation where inserting an element of a different class/id breaks all css-rules on that :first-child.

<div id="nav">
    <div class="nSub">abcdef</div>
    <div class="nSub">abcdef</div>
    <div class="nSub">abcdef</div>
    <div class="nSub">abcdef</div>
    <div class="nSub">abcdef</div>
</div>


.nSub:first-child { margin-top:15px; -moz-border-radius-topleft:5px; /* ... */ }
.nSub             { background:#666; /* ... */ }
.nSub:last-child  { -moz-border-radius-bottomleft:5px; /* ... */ }

As soon as I insert an element of another class/id above, like this:

$('nav').insert({top:'<div id="newWF"></div>'});

all declarations for .nSub:first-child are being ignored in both FF 3.6 and Safari 4.

EDIT: sorry if I did not say it clearly: the element inserted above is supposed to NOT have the classname ".nSub"

<div id="nav">
    <div id="newWF"></div>
    <div class="nSub">abcdef</div> <!-- BROKEN CSS -->
    <div class="nSub">abcdef</div>
    <div class="nSub">abcdef</div>
    <div class="nSub">abcdef</div>
    <div class="nSub">abcdef</div>
</div>

Solution

  • That's because the first element with class nSub is no longer the first-child of the parent, and thus the style no longer matches.

    If the dynamically inserted element would also have class nSub, then the rule would still match, and match for the newly inserted element (which is now the first child).

    I'm no CSS3 expert, but you could try the :nth-of-type selector:

    .nSub:nth-of-type(1) {
       /* Rules for the first .nSub here */
    }