Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting every 4th <div>

Tags:

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?

like image 789
Craig Jonathan Kristensen Avatar asked Jun 05 '13 19:06

Craig Jonathan Kristensen


People also ask

How do you select every 4th element in an equation?

In our above example, we selected every fourth element with the formula 4n, which worked because every time an element was checked, “n” increased by one (4×0, 4×1, 4×2, 4×3, etc). If an element’s order matches the result of the equation, it gets selected (4, 8, 12, etc).

How do I select only the 5th Element of a list?

Just a number. If you put simply a number in the parentheses, it will match only that number element. For example, here is how to select only the 5th element: Let’s get back to the 3n+3 from the original example though. How does that work? Why does it select every third element?

How do I Count div elements of different types?

If you have any other elements of different types such as h1 or p, you will need to use :nth-of-type () instead of :nth-child () to ensure you only count div elements:

How do I select every 3rd item in a list?

There is a CSS selector, really a pseudo-selector, called nth-child. Here is an example of using it: ul li:nth-child(3n+3) { color: #ccc; }. What the above CSS does, is select every third list item inside unordered lists. That is, the 3rd, 6th, 9th, 12th, etc.


1 Answers

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){
like image 186
Pevara Avatar answered Oct 21 '22 11:10

Pevara