First determine the positioning, because the width of the. Box is OK, adjust the number of columns according to the width of the screen, so the width of the #content varies with the number of columns in. box, and it needs to remain centered relative to the body.
therefore need to add positioning position:relative to #content;
and. Box positioning the first line relative no problem, in addition to the first line, the other lines need to adjust their top and left, so that they complement and to it, so the positioning of the other lines need to absolute.
So. Box does not need to set position, late dynamic for the second line above the addition of Absolute.
The displacement selection between box uses padding because it is easy to calculate the actual width and height, which is needed later.
function Waterfall () {//Calculate the width of a single box, then calculate the current window to drop a few columns of boxvar boxwidth=$ (". Box"). Outerwidth (); var Boxcol=math.floor ($ ("body"). Width ()/boxwidth);//Adjust the width of the #content so that it matches the total width of the box and is centered relative to the window$ ("#content"). Width (boxcol*boxwidth). CSS ("margin", "0 auto");//initial array to hold the total height of each column of boxvar arr=[];//Traverse all box to perform box positioning$ (". Box"). each (function (i,a) {//The first line does not need to be positioned, only the initial height valueif (i<boxcol) {arr[i]=$ (this). Outerheight (); }//second line above needs to be positioned for each box, the positioning rule is the first row of the total height of the smallest box row priority emissionselse{//Find the minimum value of the total height of all columnsvar minheight=math.min.apply (Null,arr);//Find the index value of the minimum height columnvar minindex=$.inarray (Minheight,arr);//performs absolute positioning on the currently traversed object, top is the value of the minimum height column, left is the current left of the minimum height column$ (this). css ({' position ': ' absolute ', ' top ': minheight+ ' px ', ' left ' : minindex*boxwidth+ ' px '});//Resets the value of the minimum height column, plus the height of the currently traversed objectarr[minindex]+=$ (This). Outerheight (); } }); }
Waterfall Flow Layout--jquery