- 宽度一致,高度不同
- 根据父元素宽度以及每列宽度计算出列表个数,列表默认0
- 图片依次放在最短列的下面
- 父容器高度取列表最大值
- 父元素相对定位,子元素绝对定位

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
box-sizing: border-box;
margin: 0;
}
.main{
width: 90%;
height: 600px;
background-color: #efefef;
margin: 10px auto;
position: relative;
}
.box{
width: 200px;
display: inline-block;
margin: 10px;
position: absolute;
}
.box1{
height: 160px;
background-color: gray;
}
.box2{
height: 250px;
background-color: pink;
}
.box3{
height: 199px;
background-color: yellowgreen;
}
.box4{
height: 110px;
background-color: burlywood;
}
</style>
</head>
<body>
<div class="main">
<div class="box box3">1
</div><div class="box box2">2
</div><div class="box box4">3
</div><div class="box box1">4
</div><div class="box box4">5
</div><div class="box box2">6
</div><div class="box box4">7
</div><div class="box box3">8
</div><div class="box box1">9
</div><div class="box box4">10
</div><div class="box box2">11
</div><div class="box box4">12
</div><div class="box box3">13
</div><div class="box box1">14
</div><div class="box box4">15
</div>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
function reset(){
var boxWidth = $('.box').width()+20
var mainWidth = $('.main').width()
var colCount = Math.floor(mainWidth/boxWidth) //列数
var paddingLeft = (mainWidth-boxWidth*colCount)/2
var colHeightArry = []
for(var i=0 ; i<colCount ; i++){
$('.box')[i].style.top = 10
$('.box')[i].style.left = (boxWidth*i)+paddingLeft+"px"
colHeightArry[i]=$($('.box')[i]).height() //每列的高度
}
for(var j = colCount ; j < $('.box').length ; j++){
$($('.box')[j]).each(function(){
var minHeight = colHeightArry[0],minIndex = 0
for(var i = 1 ; i < colCount ; i++){
if(colHeightArry[i]<minHeight){
minHeight = colHeightArry[i]
minIndex = i
}
}
$(this).css({ left:minIndex*boxWidth+paddingLeft , top: minHeight+10 })
colHeightArry[minIndex] += $(this).height()+10
})
}
var maxHeight=0,maxIndex=0
for(var i = 0 ; i < colCount ; i++){
if(colHeightArry[i]>maxHeight){
maxHeight = colHeightArry[i]
maxIndex = i
}
}
var mainHeight = colHeightArry[maxIndex]+20
$('.main').css('height',mainHeight)
}
$(window).on('load',function(){
reset()
})
</script>
</body>
</html>