Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Select doubles using nth-child() in CSS3

Select doubles using nth-child() in CSS3

Problem

Say I have the following structure for a list:

and each

  • is 50% width so I want every two to have the same background colour like this:

    Can I do this using the 'nth-child()' CSS selector so as to minimise code?

    Problem courtesy of: Dan
  • Solution

    ul li:nth-child(4n+1),
    ul li:nth-child(4n+2) {
      background: #CCC;
    }
    ul li:nth-child(4n+3),
    ul li:nth-child(4n+4) {
      background: #DDD;
    }
    

    This will give you every 4th element starting with the 1st, and 2nd as color #CCC and every 4th element starting with the 3rd and 4th as #DDD

    jsfiddle here: http://jsfiddle.net/mU2tn/1/

    Solution courtesy of: jzworkman

    Discussion

    View additional discussion.



    This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

    Share the post

    Select doubles using nth-child() in CSS3

    ×

    Subscribe to Css3 Recipes - The Solution To All Your Style Problems

    Get updates delivered right to your inbox!

    Thank you for your subscription

    ×