Forum Moderators: not2easy
.pages
{
background-color: red;
}
.category
{
background-color: green;
}
.category:first-of-type
{
background-color: blue;
}
.category:last-of-type
{
background-color: white;
}
.group
{
background-color: yellow;
} With this HTML:
<div class="pages">
pages div
</div>
<div class="category">
first category
</div>
<div class="category">
middle category
</div>
<div class="category">
last category
</div>
<div class="group">
group div
</div> Would ideally produce in sequence red, green, blue, white, and yellow divs.
However, the divs targeted with :first-of-type and :last-of-type selectors are unaffected, and their background-color remains green.
However, if you use .category:nth-of-type(2), then the second div will be targeted. That is ,the first div with the category class.
Is this the correct behaviour? If so, is there another way to target the first element of a certain class?
Thanks!
[edited by: DeathRay2K at 6:52 pm (utc) on Jan. 18, 2009]
They are in fact CSS3
[w3.org...]
AFAIK at lease some of it is supported in Opera and Safari (+chrome)
You might be able to get more out of the :first-child pseudo class, which is
in CSS2.1 (but don't hold your breath: IE might not be cooperative - think IE7.js solves it in most if not all cases)
first-child isn't really what I'm looking for... Then I'd have to put each set inside another element, and it just gets a little messier than it should be.
[edited by: DeathRay2K at 4:37 am (utc) on Jan. 19, 2009]
:nth-of-type() pseudo-classThe :nth-of-type(an+b) pseudo-class notation represents an element that has an+b-1 siblings with the same element name before it in the document tree, for a given zero or positive integer value of n, and has a parent element. In other words, this matches the bth child of that type after all the children of that type have been split into groups of a elements each. See :nth-child() pseudo-class for the syntax of its argument. It also accepts the 'even' and 'odd' values.
Element name in your example is "div", it's not the class name ...
Though, if you look at it, all the selectors are defined that way (as affecting the specified element), but mostly they also use the selectors preceding them as their target.
[edited by: DeathRay2K at 5:00 am (utc) on Jan. 19, 2009]
E.g.: something like
.pages+.category
selects a .category that has a .sibling right in front of it.
.category+.category
selects all but the first one of a series
If you know how many there are
.category+.category+.category selects the 3rd in a series of 3, which is the last (it selects the two last ones of a series of 4)
The "+" is supported widely, but not in IE6 (no surprise there I guess)
Edit: Scratch that, I still don't know how to target the last of each set...
[edited by: DeathRay2K at 6:49 am (utc) on Jan. 19, 2009]