views:

44

answers:

2

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>
+1  A: 

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 */
}
PatrikAkerstrand
The element which was the first-child of the class .nSub before inserting another element (with another class/id!) is afterwards technically still the first element with the class .nSub.
koko
True, but the pseudo-selector :first-child will only match the first child of an element, it does not consider classes and so on. So when you say .XYZ:first-child, you are saying "Match the first child of an element, where the first child also has the class XYZ"
PatrikAkerstrand
So, when I insert an element with another class/id above, my selector cannot match the .nSub element? By the way, I get the same result when using :nth-of-type(1).
koko
A: 
faileN
It's supposed to be another element.
koko
So you don't have to wonder, why it's not working... :)
faileN
I think you didn't get me right. the element #newWF is supposed to not look like the .nSub elements.
koko
Yepp you are right, I got the wrong unterstanding of your problem. Unfortunately I have no solution yet.
faileN