CSS实现正方形展示图片
需求
在日常开发中, 经常能遇到图片, 或者某些元素按照等分排列, 比如微信朋友圈的图片总是以九宫格的样子出现, 三等分好实现, 难点在于如何做出正方形,使得高度等于宽度
解决方案
- 用js实现, 动态计算出宽度,重置元素高度
- CSS实现, 代码如下
利用flex布局, 0 0 33.3% 使得每行三个
height对应的是父容器的height,父容器没有height(默认0), 所以不能用height 100%;
但是padding 对应的是父容器的weight,父容器width有值(33.3%), 所以可以用padding-bottom: 100% (这里不能用padding-top);
如果是正方形, 只需把height限死在0;
如果想在div内放图片, 会发现这样的方式无法正常显示图片, 因为div是被撑满的, image无法设置height为100%; 解决方案就是给div设置relative,给image设置absolute;
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
56
57
58
59
60
61
62
63
64
65
66
67
68
| <!DOCTYPE html>
<html lang="en" >
<head >
<meta charset="UTF-8" >
<title >Title</title >
<style >
.container {
display : flex;
flex-wrap : wrap;
width : 400px;
}
.item {
flex : 0 0 calc(100% / 3);
}
.content {
padding-bottom : 100%;
background : cornflowerblue;
position : relative;
}
.box {
/*height : 100%;*/
padding-bottom : 100%;
margin-right : 2px;
margin-top : 2px;
/*margin : 2px;*/
height : 0;
/*width : 100%;*/
}
.box img {
/*top : 0;*/
height : 100%;
width : 100%;
overflow : hidden;
object-fit : cover;
position : absolute;
}
</style >
</head >
<body >
<div class="container" ></div >
</body >
<template id="template" >
<div class="item" >
<div class="box" >
<div class="content" >
<img src="https://naive-ui.oss-cn-beijing.aliyuncs.com/carousel-img/carousel1.jpeg" alt="" >
</div >
</div >
</div >
</template >
<script >
const template = document.querySelector('#template').innerHTML
let html = ''
for (let i = 0; i < 9; i++) {
html += template
}
document.querySelector('.container').innerHTML = html
</script >
</html >
|