Henrik Petterson Henrik Petterson - 3 years ago 169
CSS Question

Break divs by using :nth-child properly

I want to stack divs next to each other and break the divs after three child elements.

Example HTML:

<div class="wrap">
<a> hello </a>
<a> hello </a>
<a> hello </a>
<a> hello </a>
<a> hello </a>
<a> hello </a>
<a> hello </a>
<a> hello </a>
<a> hello </a>
<a> hello </a>
<a> hello </a>
<a> hello </a>
</div>


CSS:

.wrap a {
float:left;
}

.wrap a:nth-child(4n) {
clear:left;
}


See jsFiddle. The first line displays fine, with 3 child divs next to each other. But the second line has 4 divs when it should have 3. How can I make it so only 3 divs are stacked next to each other using
:nth-child
properly?

Answer Source

Use nth-child(3n+1):

.wrap a {
   float:left;
}

.wrap a:nth-child(3n+1) {
   clear:left;
}
<div class="wrap">
  <a> hello </a>
  <a> hello </a>
  <a> hello </a>
  <a> hello </a>
  <a> hello </a>
  <a> hello </a>
  <a> hello </a>
  <a> hello </a>
  <a> hello </a>
  <a> hello </a>
  <a> hello </a>
  <a> hello </a>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download