CSS inline-block boxes work just like normal inline boxes when it comes to horizontal space. They tend to stay on the same line until they reach the limiting edge of their containing block. When this happens, they're just scattered without a discernible order on the next line. With jQuery we can control this behavior.
We have the following six boxes:
<div id="wrapper"> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> </div>
with the following styles:
#wrapper { width: 600px; margin: 2em auto; border: thick solid; background: silver; } div.box { width: 100px; height: 100px; margin: 1em; display: inline-block; background: gray; }
Normally we have four boxes on the first line and other two boxes on the second one due to the width specified on each box. With jQuery we can add a line break (br
) to each even box in order to get two boxes per row:
$('div.box:nth-child(even)', '#wrapper').each(function() { var $box = $(this); $('<br/>').insertAfter($box); });
You can see the demo on this page.