0

I'm using a CMS that generates a sitemap with very little styling options, basically, it won't allow me to add classes to the list items and I need them to give them different background colors.

Now I know there are first-child and last-child pseudo-classes that would allow me to style the first and last items in my list, but is there any CSS to allow me to call the other items in my list if a class can't be assigned to them?

thirtydot
  • 224,678
  • 48
  • 389
  • 349
Jane
  • 947
  • 3
  • 12
  • 25
  • The "CSS 2" in the question is confusing - is it "CSS level 2" or "CSS to"? Note that `:last-child` does not exist in CSS2, only `:first-child` does. – BoltClock Jul 18 '12 at 13:52

4 Answers4

3

Use :nth-child() from CSS3:

/* select the third element if it's an li */
li:nth-child(3) {
    background-color: yellow;
}

:nth-child() won't work in old browsers such as IE8, but there's a CSS2 workaround.

Community
  • 1
  • 1
thirtydot
  • 224,678
  • 48
  • 389
  • 349
  • 1
    I just updated a similar answer of mine with an illustration of the CSS2 workaround: http://stackoverflow.com/questions/9682521/how-do-i-get-the-nth-child-of-an-element-using-css2-selectors/9682598#9682598 – BoltClock Jul 18 '12 at 13:59
1

nth-child, nth-of-type

Examples:

selects the second item in the list

li:nth-child(2) {/*styles*/}

selects odd list items

li:nth-child(odd) {/*styles*/}

selects the 3rd, the 6th, the 9th, ... list items

li:nth-child(3n) {/*styles*/}

selects the 1st, the 5th, the 9th, ... list items

li:nth-child(4n+1) {/*styles*/}
Ana
  • 35,599
  • 6
  • 80
  • 131
1

CSS2 doesn't support :nth-child(n), maby you could make a background-image for the < ul > with the colors on the right positions. But I say screw people with old browsers ;)

Gijs
  • 2,064
  • 16
  • 21
0

With CSS2, maybe not. With CSS3, there's the nth-child() selector:

element:nth-child(2) { ... }

The above will get the second child.

jsFiddle

Otherwise, you could use JavaScript/jQuery to get the result you want. Here is a jQuery example:

$(function () {
    $('selector').eq(1).css('background', 'blue');
});​

jsFiddle

Zhihao
  • 14,758
  • 2
  • 26
  • 36