Jane
Jane

Reputation: 987

CSS: styling list items based on the order in which they appear rather than on classes?

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?

Upvotes: 0

Views: 132

Answers (4)

Ana
Ana

Reputation: 37179

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*/}

Upvotes: 1

Zhihao
Zhihao

Reputation: 14747

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

Upvotes: 0

Gijs
Gijs

Reputation: 2082

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 ;)

Upvotes: 1

thirtydot
thirtydot

Reputation: 228192

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.

Upvotes: 3

Related Questions