css3 nth child question
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!
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>
精彩评论