How Pinterest's Ingenious Div Stacking Layout Adapts to Different Browser Sizes
Pinterest's captivating visual layout has played a significant role in its success as a social media platform. A key aspect of this layout is the ability for the columns to adjust their number and stack vertically, regardless of the height of adjacent columns.
Behind the Scenes: Custom jQuery and CSS
The website's code reveals that this layout is achieved using absolute div positioning. However, as stated by a co-founder on Quora, Pinterest employs customized jQuery and CSS to control the layout's behavior.
The Layout Blueprint
The jQuery script, ingeniously devised, relies on the following principles:
-
Absolute Positioning: Each pin container is positioned absolutely, allowing for precise control over placement.
-
Column Width Calculation: The script calculates the width of each column based on the size of the parent container and the desired number of columns.
-
Margin Between Columns: A gutter value is defined, representing the margin between adjacent columns.
-
Height Array: An array is created to store the height of each column, which will be used to determine the vertical stacking.
-
Looping Through Pins: As new pins are added, the script iterates through each one, placing it within the shortest column.
-
Setting Coordinates: Each pin's left position is set to its respective column index multiplied by the column width plus the gutter. Its top position corresponds to the height of the shortest column at that instance.
-
Height Adjustment: After placing the pin, its height is added to the height of the chosen column in the array.
Benefits of the Custom Layout
This custom layout offers several advantages:
-
Responsive: The layout automatically adjusts based on browser size changes, providing an optimal viewing experience.
-
Vertical Stacking: Independent of adjacent column heights, the pins stack vertically, creating a grid-like effect.
-
Efficiency: The script is highly efficient, reducing the time it takes to layout multiple pins on a page.
The above is the detailed content of How Does Pinterest Achieve Its Responsive Layout With Div Stacking?. For more information, please follow other related articles on the PHP Chinese website!