views:

125

answers:

1

Hello. I am designing a 960px wide layout with an unordered list. Each list item is 240px wide, so 4 list items fit horizontally in a row. I have about 20 rows on the page....

I want every other list item to have a background of #ececec, so my css would be:

ul li:nth-child(2n+2){
    background-color:#ececec;
}

This works. The only problem is because there are 4 items in a row (an even #), the next row would be identical, thus rendering background colors on every 1st and 3rd list items in a row. This is not the effect I am looking to achieve. I want the background colors to alternate, creating a grid-like effect. What is the correct css to do so (think a checker board). Thanks!

A: 

If you want a checkerboard, then use:

ul li:nth-child(8n+1), ul li:nth-child(8n+3), ul li:nth-child(8n+6), ul li:nth-child(8n+8) {
    background-color:#ececec;
}

The pattern repeats every two rows, which in your case is every 8 elements, so you need 8n in the selector. And of those eight, you want the 0th, 2nd, 5th and 7th to have the alternate color.

EDIT: I tried this HTML, and got a checkerboard in Firefox 3.5.9:

<html>
<head>
<style>
#container {
    width: 960px;
    border: 1px solid black;
}
span {
    border: 1px solid gray;
    display: block;
    width: 180px;
    float: left;
    padding: 10px;
    margin: 10px;
    background: blue;
}
span:nth-child(8n+1), span:nth-child(8n+3), span:nth-child(8n+6), span:nth-child(8n+8) {
    background: red;
}
</style>
<body>
<div id='container'>
    <span>One</span>
    <span>Two</span>
    <span>Three</span>
    <span>Four</span>
    <span>Five</span>
    <span>Six</span>
    <span>Seven</span>
    <span>Eight</span>
    <span>Nine</span>
    <span>Ten</span>
    <span>Eleven</span>
    <span>Twelve</span>
    <span>Thirteen</span>
    <span>Fourteen</span>
    <span>Fifteen</span>
    <span>Sixteen</span>
    <span>Seventeen</span>
    <span>Eighteen</span>
</div>
Ned Batchelder
Counter-intuitively, `nth-child` is 1-based.
bobince
cant seem to get this to work. still loads the exact same. gonna give it a few more tries
JCHASE11
i have tried both suggestions with every possible combination and its still not working...any ideas?
JCHASE11
@bobince, thanks, I've changed the numbers to be 1-based. @JCHASE, I've added sample code.
Ned Batchelder
thanks, that did it
JCHASE11

related questions