Fluid grids with jQuery and CSS

Fluid grids with jQuery and CSS

How to create responsive grids using jQuery and CSS table values.

Fluid grids can be built using many approaches. One of the most interesting techniques is related to the use of CSS table values for the display property. The main problem with this approach is that all the items must be wrapped within one or more table rows. If we don't do so, we'll simply see a single row containing all the items inserted in the main wrapper. But here jQuery comes to the rescue.

Consider the following markup:


<div id="content">
    <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>

We want to create a fluid grid with three items per row. If we use table values, we have also to use the border-collapse, border-spacing and border properties in order to create some spacing between each block:


#content {
    width: 90%;
    margin: 2em auto;
    display: table;
    border-collapse: separate;
    border-spacing: 2%;
}
.box {
    width: 32%;
    display: table-cell;
    height: 15em;
    background: #ccc;
    border: 1em solid #fff;
}

/* For jQuery */
.row {
    display: table-row;
}

At this point we have all the six items on the same row. With jQuery we simply have to insert a break using the modulus operator:


$(function () {
    $('div.box', '#content').each(function (i) {
        var $div = $(this);
        var index = i + 1;

        if (index % 3 == 0) {
            $('<div class="row"/>').insertAfter($div);
        }

    });

});

[view-example url="http://jsfiddle.net/gabrieleromanato/abQSC/"]