jQuery isotope centering

user1130217 picture user1130217 · Aug 26, 2012 · Viewed 14k times · Source

Possible Duplicate:
How to center DIV in DIV?

Please take a look at the image below:

enter image description here

How can I make the grey squares horizontally centered inside the red container div? This is all made with isotope, so please keep that in mind.

Thanks in advance.

enter image description here enter image description here

Even if the parent (red) div is always aligned in the middle, the grey, smaller ones are not. In the top image, when they are aligned in one single column, that column should be in the exact middle of the wrapper (red) div.

Answer

Systembolaget picture Systembolaget · Aug 26, 2012

It's actually very simple to implement centering for Isotope (just finished a site that does this to look good on mobile touch devices as well as desktop devices). You just include this bit of code from David DeSandro's repository before the usual Isotope code at the end of this block

<!-- centered layout extension http://isotope.metafizzy.co/ --> 

<script type="text/javascript">
$.Isotope.prototype._getCenteredMasonryColumns = function() {

    this.width = this.element.width();

    var parentWidth = this.element.parent().width();

    var colW = this.options.masonry && this.options.masonry.columnWidth || // i.e. options.masonry && options.masonry.columnWidth

    this.$filteredAtoms.outerWidth(true) || // or use the size of the first item

    parentWidth; // if there's no items, use size of container

    var cols = Math.floor(parentWidth / colW);

    cols = Math.max(cols, 1);

    this.masonry.cols = cols; // i.e. this.masonry.cols = ....
    this.masonry.columnWidth = colW; // i.e. this.masonry.columnWidth = ...
};

$.Isotope.prototype._masonryReset = function() {

    this.masonry = {}; // layout-specific props
    this._getCenteredMasonryColumns(); // FIXME shouldn't have to call this again

    var i = this.masonry.cols;

    this.masonry.colYs = [];
        while (i--) {
        this.masonry.colYs.push(0);
    }
};

$.Isotope.prototype._masonryResizeChanged = function() {

    var prevColCount = this.masonry.cols;

    this._getCenteredMasonryColumns(); // get updated colCount
    return (this.masonry.cols !== prevColCount);
};

$.Isotope.prototype._masonryGetContainerSize = function() {

    var unusedCols = 0,

    i = this.masonry.cols;
        while (--i) { // count unused columns
        if (this.masonry.colYs[i] !== 0) {
            break;
        }
        unusedCols++;
    }

    return {
        height: Math.max.apply(Math, this.masonry.colYs),
        width: (this.masonry.cols - unusedCols) * this.masonry.columnWidth // fit container to columns that have been used;
    };
};
</script>

And then you just set up Isotope as usual

<script type="text/javascript">
$(function() {
    var $container = $('#container');
    // the usual stuff for layouting, sorting, filtering, limiting clicks to zones...
</script>