Ben - good point, I completely forgot about that quirk of
first-child... that it selects the p if it *is* the first child of the
div rather than the first child of the dic which is a P tag - which
rally should be the way it works in my opinion... would make things a
lot more flexible.
I should point out that the javascript function I wrote above exhibits
this behaviour, so feel free to pinch and adapth if you want.
Of course this is all academic because none of the solutions given
[using sibling selectors etc] will work in IE6 so you need to come up
with something that degrades.
Howa, if you know for absolute certain that a <pwill always be the
first child of your div.main then you don't have an issue - if it can
vary then you are in a world of pain - just add the class attribute and
be done with it.
Of course, if you only have a certain combination of alternatives from
the one given then you can always have different selectors that do the
same thing:
eg: if you end up with this say:
<div class="main">
<h1>Some heading</h1>
<p>sssss</p>
<p>sssss</p>
<p>sssss</p>
<p>sssss</p>
</div>
then "div p:first-child {...}" won't work
However if you added a variation on what Johannes suggests so you have
div.main h1 + p { ... }
then this will work and select the p which is a sibling of the h1 which
are children of the div.main - if you have a limited number of cases
which you can guarantee will always be the case [which in using
semantic HTML you probably can] then you haven't got an issue - though
as Ben says, this is quite brittle in that an extra tag in the wrong
place will break it.
This does bring us full circle again however, which is that none of
this has any support in IE6 so if having the first child selected is of
vital importance and is crucial to your design you'll need another way
of doing it and the only relaible way is to add an id or class
attribute.
I've mentioned this elsewhere recently but it would be good if CSS used
selection methods more akin to XPath [considering the node trees work
the same way] as you'd get a lot more out of it - that's what happens
when there is more focus on the style part of the spec than the
selection part!
Cheers
AndrewF
www.xmlinfinity.com - content management where the possibilites are
endless.
Harlan Messinger wrote:
Jukka K. Korpela wrote:
Scripsit Johannes Koch:
p {
/* rules for first p */
}
p+p {
/* overwrite rules for other p elements */
}
Nice, but it doesn't work if there's any element between p elements. If
you have, say,
<p>...</p>
<p>...</p>
<hr>
<p>...</p>
<p>...</p>
then the rules for "first p" will apply to the p element after the hr
element, too.
How about *+p?