Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS CSS Basics (2014) Basic Selectors Descendant Selectors

What if you want a banded color for your ordered or unordered list?

In the video, Gull gave an example of using the descendant selectors on an ol and ul with a background color behind the entire list. What if you had 4 list items and you wanted lets say 2 of them to have background color of purple and 2 of them to have a background color of yellow but alternating as a banded list, so it's

list item 1 purple bkg list item 2 yellow bkg list item 3 purple bkg list item 4 yellow bkg

How would this be written in the stylesheet?

2 Answers

Flor Antara
Flor Antara
12,372 Points

Hi Zachary,

That is a great question!

To achieve that effect, you would use :nth-child(even) and :nth-child(odd)to target theli`s.

You can have them all with a purple background, and then you can change the color of the "even" ones only for instance.

Example:

li{
    background-color: purple;
}
li:nth-child(even){
    background-color: yellow;
}

Perfect, that helps so much! Thank you!

I highly doubt this would ever be applicable but what if there were 3 colors you wanted to alternate? Lets say purple, yellow and red, I assume you wouldn't be able to use the even and odd :nth-child. So just for example, again I highly doubt something like this would ever be put into play especially because it would look terrible but:

list item 1 purple bkg

list item 2 yellow bkg

list item 3 red bkg

list item 4 purple bkg

list item 5 yellow bkg

list item 6 red bkg

How would this be written to alternate between 3 (or more) colors for the lists

To do it for different numbers instead of just odd or even you use the an+b syntax.

See the MDN docs on :nth-child for more info.

In your example, you would use the following:

li:nth-child(3n+1) {
    background-color: purple;
}
li:nth-child(3n+2) {
    background-color: yellow;
}
li:nth-child(3n) {
    background-color: red;
}