Nth-Child Element Counting Items
I have a problem when nth-child(3n+1)
counting my intervals. This is what I mean:
#main .item {
display: block;
float: left;
width: 100px;
height: 100px;
margin: 0 10px 10px 0;
background-color: red;
}
span.clear {
display: block;
clear: both;
}
#main > div:nth-child(3n+1) {
background-color: blue;
}
<div id="main">
<div id="one" class="item"></div>
<div id="two" class="item"></div>
<div id="three" class="item"></div>
<span class="clear"></span>
<div id="four" class="item"></div>
<div id="five" class="item"></div>
<div id="six" class="item"></div>
<span class="clear"></span>
<div id="seven" class="item"></div>
<div id="eight" class="item"></div>
<div id="nine" class="item"></div>
</div>
It should paint the following squares:
- 3 * 0 + 1 = 1
- 3 * 1 + 1 = 4
- 3 * 2 + 1 = 7
But for some reason, in all my browsers and tests, I am returning this:
- Square 1 gets color
- Square 6 is colored
- Square 8 is colored
I have no idea why this happens differently than counting the range or maybe I'm misinterpreting nth-child
can someone explain in detail what is going wrong and why I am not getting the expected results?
source to share
You want :nth-of-type
, not:nth-child
#main .item {
display: block;
float: left;
width: 100px;
height: 100px;
margin: 0 10px 10px 0;
background-color: red;
}
span.clear {
display: block;
clear: both;
}
#main > div:nth-of-type(3n+1) {
background-color: blue;
}
<div id="main">
<div id="one" class="item">1</div>
<div id="two" class="item">2</div>
<div id="three" class="item">3</div>
<span class="clear"></span>
<div id="four" class="item">4</div>
<div id="five" class="item">5</div>
<div id="six" class="item">6</div>
<span class="clear"></span>
<div id="seven" class="item">7</div>
<div id="eight" class="item">8</div>
<div id="nine" class="item">9</div>
</div>
Your formula :nth-child(3n+1)
will select 1, 4, 7, 10, children of #main if they are divs. So what happens is that the first child of #main is a div. Great, it's chosen correctly and colored blue. Then the fourth child is selected. Unfortunately, this is a span, not a div, so it is ignored. The seventh child is a div (with a hex id) and since it selects the div, although not in the way you hoped. Think about it right to left. div:nth-of-type(3n+1)
will loop through the children of #main, selecting elements 1, 4, 7, 10 and then applying the selected properties if that element is a div.
source to share
As mentioned in other answers, you should use :nth-of-type
instead, but you can still use :nth-child
if you remove anything blank span
from the markup (blank markup just for styling purposes is never a good idea, especially in terms of code reliability), and if you change the style this way
#main > div:nth-child(3n+1) {
background-color: blue;
clear: left;
}
source to share