Reputation: 20834
How to select every first and fourth div
with the :nth-child
selector to add a specific style to it ?
.main{
width:460px;
height:240px;
}
.box{
width:100px;
height:100px;
background:red;
float:left;
margin:10px;
}
/*I tried */
.box:nth-child(n+4),.box:first-child{
margin:10px 10px 10px 0;
}
.box:nth-child(4n){
margin:10px 0px 10px 10px;
}
<div class="main">
<div class="box"></div> <!-- margin-left:0px -->
<div class="box"></div>
<div class="box"></div>
<div class="box"></div> <!-- margin-right:0px -->
<div class="box"></div> <!-- margin-left:0px -->
<div class="box"></div>
<div class="box"></div>
<div class="box"></div> <!-- margin-right:0px -->
</div>
The second code works, but I am having trouble with the first ?
How to select every first and last div in the row (rows contains four divs)?
Upvotes: 0
Views: 3021
Reputation: 180
If you need IE8 or below support, than you should use the selector in Jquery. Using your example:
$('.box:nth-child(4n+1)').css('background-color', 'yellow');
Upvotes: 0
Reputation: 23208
4n will select 4, 8, 12 ....
4n+1 will select 1, 5, 9, 13, ...
Using a formula (an + b). Description: a represents a cycle size, n is a counter (starts at 0), and b is an offset value.
.box:nth-child(4n){
margin:10px 0px 10px 10px;
}
.box:nth-child(4n+1){
margin:10px 10px 10px 0;
}
Upvotes: 5
Reputation: 5845
Try this:
.box:nth-child(4n+1){
background-color:yellow;
margin-left:0;
}
.box:nth-child(4n){
background-color:blue;
margin-right:0;
}
Upvotes: 1
Reputation: 7092
.box:nth-child(4n){
background: blue;
}
.box:nth-child(4n+1){
background: orange;
}
Upvotes: 2
Reputation: 5210
Try this:
.box:nth-child(4n+1)
That should include the first (+1
) element and then every fourth (4n
).
Upvotes: 6