stepquick
stepquick

Reputation: 398

Styling with nth-child

What I'm trying to accomplish is, the first two sections are white, followed by two grey sections, then that pattern continues.

I made a jsfiddle to show what I have so far: jsfiddle

CSS:

section{
      float:left;
      width:40%;
      background:#ccc;
      padding:20px 25px;
      margin-bottom:2px
}
section:nth-child(even){
      margin-left:2px;
}
section:nth-child(1),
section:nth-child(2n+2){
      background:#fff;
}

HTML:

<section></section>
<section></section>
<section></section>
<section></section>
<section></section>
<section></section>
<section></section>
<section></section>

Would I need to use another :nth-child() to make this work correctly? Or would this be better to use jquery for?

PHP is being used to generate these boxes, so would a php approach be the best way? Maybe classes?

Upvotes: 0

Views: 127

Answers (2)

j08691
j08691

Reputation: 207861

Try this:

section {
    float:left;
    width:40%;
    background:#fff;
    padding:20px 25px;
    margin-bottom:2px
}
section:nth-child(even) {
    margin-left:2px;
}
section:nth-child(4n),section:nth-child(4n-1) {
    background:#ccc;
}

jsFiddle example

Upvotes: 2

cimmanon
cimmanon

Reputation: 68319

Nth-child is what you want, but what you're looking for is like this:

http://tinker.io/f5c5c

section:nth-child(4n+1),
section:nth-child(4n+2){
      /* styles here */

}

Upvotes: 4

Related Questions