Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replicate pinterest.com's absolute div stacking layout [closed]

Tags:

jquery

css

layout

I am looking to replicate Pinterest.com's div layout, specifically how the number of columns adjusts to fit more/less on browser resize and the vertical stacking is not dependent on adjacent column heights. The source code shows that each div is position absolute. A co-founder has answered a Quora post stating it is done with custom jQuery and CSS. I would like the results sorted left to right. Any direction you could provide to make it myself would be greatly appreciated.

like image 516
chrickso Avatar asked Aug 18 '11 14:08

chrickso


3 Answers

I wrote the Pinterest script. The ID's are unrelated to the layout, and are used for other interaction-related JS. Here's the base of how it works:

Beforehand:

  • Absolutely position the pin containers
  • Determine column width
  • Determine margin between columns (the gutter)

Setup an array:

  • Get the width of the parent container; calculate the # of columns that will fit
  • Create an empty array, with a length equaling the # of columns. Use this array to store the height of each column as you build the layout, e.g. the height of column 1 is stored as array[0]

Loop through each pin:

  • Put each pin in the shortest column at the moment it is added
  • "left:" === the column # (index array) times the column width + margin
  • "top:" === The value in the array (height) for the shortest column at that time
  • Finally, add the height of the pin to the column height (array value)

The result is lightweight. In Chrome, laying out a full page of 50+ pins takes <10ms.

like image 68
Evan Sharp Avatar answered Oct 14 '22 10:10

Evan Sharp


You could also check on the jQuery Plug-in Masonry, for this kind of functionality.

like image 79
Bob. Avatar answered Oct 14 '22 10:10

Bob.


We released a jQuery plugin because we got the same question several times for Wookmark. It creates exactly this type of layout. View it here - Wookmark jQuery plugin

like image 56
GBKS Avatar answered Oct 14 '22 11:10

GBKS