Monday, September 17, 2012

Centralize a Tile based view

A project that I'm working on has a structure similar to what you seen in Pinterest. Except that the height of the Tiles do not vary as in Pinterest.

What happens essentially in Pinterest is that the Tiles are positioned absolutely. The Tiles are given left and top css properties and are positioned according with resize handlers.

But in this application, the height of the Tile is static. Therefore we could accomplish this with CSS and some javascript. One knows the width of the Tile (Look at Jquery's outerWidth) and the width of the window (Look at Jquery's width). One just has to set up a resize handler (Look at Jquery's resize) and do something similar to this.

var base = $('#content_wrapper'), window_width, post_width; 
if(base.length !== 0) { 
 window_width = $(window).width();
 post_width = $('.post:first').outerWidth(true); 
 if(window_width%post_width !== 0) {
  base.css({'width': window_width - (window_width%post_width)}); 
 } else { 
  base.css({'width': window_width}); 
 } 


$(window).resize(function() { 
 // Call the function here .. 
});

We will also need to call the function when the page loads too for the initial set up.