Take a look at this plugin http://isotope.metafizzy.co/, may solve your problem.
It has several layout options, but maybe the one Voc6e is interested in is the Masonry
. In it the blocks of different size are embedded, as if it were a brick wall (hence the name). A documentation describes like this:
Masonry is the default layout in Isotope. The elements are organized intelligently within a vertical grid. For each element, the script calculates the best position within the grid.
The algorithm that determines the position of the elements is this one:
_masonryLayout : function( $elems ) {
var instance = this,
props = instance.masonry;
$elems.each(function(){
var $this = $(this),
//how many columns does this brick span
colSpan = Math.ceil( $this.outerWidth(true) / props.columnWidth );
colSpan = Math.min( colSpan, props.cols );
if ( colSpan === 1 ) {
// if brick spans only one column, just like singleMode
instance._masonryPlaceBrick( $this, props.colYs );
} else {
// brick spans more than one column
// how many different places could this brick fit horizontally
var groupCount = props.cols + 1 - colSpan,
groupY = [],
groupColY,
i;
// for each group potential horizontal position
for ( i=0; i < groupCount; i++ ) {
// make an array of colY values for that one group
groupColY = props.colYs.slice( i, i+colSpan );
// and get the max value of the array
groupY[i] = Math.max.apply( Math, groupColY );
}
instance._masonryPlaceBrick( $this, groupY );
}
});
}
From what I could understand what’s going on:
- The grid is started with a list of initial positions of each column. Ex:
[0, 0, 0, 0]
- For each element, the algorithm determines which columns it would fit into, based on width. So, if there are 5 columns, an element with a width of 3 columns, it can enter columns 1 or 2.
- In each of the columns possible to fit the element, it is verified which place louder where it is possible to insert it.
- The element is inserted in the highest possible spaces, and the first available position of the columns it occupies is updated.
It’s a weird process to explain, but very simple to visualize, if you see the examples on the Isotope website. Or, better yet, if I ride one for you and poke at it.
Hello Leandro, very top this plugin. It will serve as reference also for future works, but I liked masonry more for being free and much simpler
– Douglas Cabral