jQuery: taming the horizontal space of CSS inline-block boxes

jQuery: taming the horizontal space of CSS inline-block boxes

How to manage with jQuery the horizontal space of CSS inline-block elements.

Inline-block elements are hybrid CSS boxes which are normally aligned horizontally as inline elements but their box is formatted using a block-level formatting context. These elements move on the next line only when they reach the outer edge of their containing block. Using only CSS to make them align differently is not possible: for example, adding a new line via generated content to all even boxes to make them appear on several lines has no effect on them because CSS generated content works only internally. For that reason we have to use jQuery.

We have the following structure:


<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;
}
​

The main container is 600 pixels wide. The inline-block boxes are 100 pixels wide plus a 32 pixels given by the sum of their horizontal margins. Their resulting total width is 132 pixels, which means that we'll have 4 boxes on the first line and the last two boxes on the second line.

To create three lines with two boxes on each line we have to insert a line-break (br) just after each even box:


$('div.box:nth-child(even)', '#wrapper').each(function() {
    var $box = $(this);
    $('<br/>').insertAfter($box);
});​

You can see the demo on this page.