* {margin: 0; padding: 0;}html, body {width: 100%; height: 100%; background-color: #EDEDED;}#main { position: relative; width: 1280px; /*限定父容器的宽度*/ margin: 0 auto; }.box { position: absolute; padding: 7px; /*不建议使用 margin*/ box-sizing: border-box; width: 256px; /*限定数据块的宽度*/}.wrapper { padding: 5px; background-color: #fff; border: 1px solid #e4e4e4; box-shadow: 0 1px 5px rgba(0, 0, 0, .2); }.pic { font-size: 0; /*消除行内元素的间隙*/}.pic img { width: 100%; height: auto; }.text { color: #999; background: #FAFAFA; font-size: 14px; padding-top: 5px; }
window.onload = function() { waterFall('main', 'box') } function waterFall(main, box) { var main = document.getElementById(main); var boxs = main.getElementsByClassName(box); var boxWidth = boxs[0].offsetWidth; //获取每个数据块的宽度 var mainWidh = main.offsetWidth; //获取主容器的宽度 var cols = Math.floor(mainWidh / boxWidth); //计算列数 var heightArr = []; //定义一个存放 top 值的数组 for(var i = 0; i < boxs.length; i++) { var boxHeight = boxs[i].offsetHeight; if(i < cols) { //第一行 heightArr.push(boxs[i].offsetHeight); boxs[i].style.top = '0px'; boxs[i].style.left = i * boxWidth +'px'; } else { //求出最矮盒子的高度 var minBoxHeight = Math.min.apply(this, heightArr); //求出最矮盒子的索引 var minBoxIndex = getIndex(minBoxHeight, heightArr); boxs[i].style.top = minBoxHeight + 'px'; //顶部间距即最矮盒子的高度 boxs[i].style.left = minBoxIndex * boxWidth +'px'; //关键:更新最矮盒子的高度 heightArr[minBoxIndex] += boxHeight; } } } function getIndex(val, arr) { for(var i in arr) { if(val == arr[i]) { return i; } } }
#main { width: 1280px; margin: 0 auto; -webkit-column-count: 5; column-count: 5; -webkit-column-gap: 0; column-gap: 0; }.box { padding: 7px; box-sizing: border-box; width: 256px; }
How to define the minimum height of the inline element span
How to use the html area image hotspot
What are the operations of borderless and borderless iframes
How to use image to submit form
The above is the detailed content of Two methods to implement waterfall flow layout. For more information, please follow other related articles on the PHP Chinese website!