Selecting every 4th <div>

I have a long line of DIVs and I need to change the padding on every 4th DIV using the nth-child selector, but I am having problems getting it to work at all.

Here is my css:

.content_tab {
    width: 220px;
    height: 340px;
    margin-right: 20px;
    margin-bottom: 20px;
    float: left;
    background-color: #0F0;
}
.content_tab:nth-child(4){
    background-color: #F00;
    margin-right: 0px;
}

and here is my HTML:

<div class="content">
    <div class="content_tab"></div>
    <div class="content_tab"></div>
    <div class="content_tab"></div>
    <div class="content_tab"></div>
    <div class="content_tab"></div>
    <div class="content_tab"></div>
    <div class="content_tab"></div>
</div>

Any ideas?

Upvotes: 23

Views: 59533

Answers (3)

Adrift
Adrift

Reputation: 59779

.content div:nth-child(4n) {  /* selects 4, 8, 12, 16, etc. */
    padding: 10px;
}

http://jsfiddle.net/y6vfg/1/

Or if you want every fourth element starting from the first you can use:

.content div:nth-child(4n + 1) { /* selects 1, 5, 9, 13 .. */
    padding: 10px;
}

http://jsfiddle.net/y6vfg/7/

Upvotes: 12

Rory McCrossan
Rory McCrossan

Reputation: 337560

To get every 4th element in the selector use 4n

.content_tab:nth-child(4n){
    background-color: #F00;
    margin-right: 0px;
}

Example fiddle

Note I made the div sizes smaller in the fiddle so it was easier to see it working.

Upvotes: 5

Pevara
Pevara

Reputation: 14310

You should change

.content_tab:nth-child(4){

To

.content_tab:nth-child(4n){

As explained here http://css-tricks.com/how-nth-child-works/

Or if you do not want the first div to be selected, you need

.content_tab:nth-child(4n+4){

Upvotes: 46

Related Questions