css3实现图片木桶布局

思路

1、容器flex布局

2、图片定高、超出换行

3、图片都设置 flex-grow: 1; 以充满整行

4、图片都设置 object-fit: cover; 以解决图片变形

5、容器 :after 伪类 设置 flex-grow: 9999; 且值足够高 以解决最后一行图片数量少时仍然充满整行过于扁长

实现效果:

这里写图片描述

html代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<!DOCTYPE html>
<script>
window.navigator.appVersion.indexOf('Trident') != -1 && alert('请用谷歌或火狐新版打开!');
</script>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
}
body{
padding: 50px 0;
overflow-x: hidden;
}
.wrap{
display: flex;
flex-wrap: wrap;
}
.wrap img{
margin: 3px;
padding: 5px;
height: 200px;
background: #ccc;
flex-grow: 1;
object-fit: cover;
transition: .3s;
}
.wrap:after{
display: block;
content: '';
flex-grow: 9999;
}
.wrap img:hover{
transform: scale(1.2);
box-shadow: 0 0 20px #fff;
z-index: 9999;
}
</style>
</head>
<body>
<div class="wrap"></div>
<script>
var wrap = document.querySelector('.wrap');
var src = ['//cdn.attach.qdfuns.com/notes/pics/201710/13/093715yf2jt47tttj9lyfj.jpg','//cdn.attach.qdfuns.com/notes/pics/201710/13/092835ebbkfzjtb4okwj2b.jpg','//cdn.attach.qdfuns.com/notes/pics/201710/13/092835beqzk6kyjkbwr5bw.jpg','//cdn.attach.qdfuns.com/notes/pics/201710/13/092835nshkii0i2k0dsikn.jpg','//cdn.attach.qdfuns.com/notes/pics/201710/13/093653k6ztcd7x7czebkfh.jpg']
for(var i=0; i<Math.floor(Math.random()*10+30); i++){
var img = document.createElement('img');
img.src = src[Math.floor(Math.random()*5)];
wrap.appendChild(img);
}
</script>
</body>
</html>
-------------本文结束感谢您的阅读-------------