scale and crop image

图片水平,垂直居中,切掉上下多余部分,高度随着宽度变化

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DIV 高度随着宽度按照比例变化 </title>
</head>
<style>
* {
box-sizing: border-box;
}
html,
body {
padding: 0;
margin: 0;
}
.out {
width: 30%;
border: 1px solid transparent;
position: relative;
}
.ratio {
width: 100%;
border: 1px solid transparent;
margin-top: 52%;
}
.img {
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
border: 1px solid transparent;
overflow: hidden;
}
.img img {
position: absolute;
margin: auto;
top: -200%;
right: -200%;
bottom: -200%;
left: -200%;
width: 100%;
}
</style>
<body>
<!--
.out 是外层的div,宽度百分比设定,高度与宽度成一定比例变化,
它是靠内部的.ratio div支撑起来的
-->
<!--
.ratio 是宽高成比例的div,
原理是利用margin在设定百分比的时候,
始终是根据父元素的width来设定的,所以height: 0px;margin-top: 52%
-->
<div class="out">
<div class="ratio">
</div>
<div class="img">
<img src="h.png" alt="">
</div>
</div>
<hr>
<div class="out">
<div class="ratio">
</div>
<div class="img">
<img src="v.png" alt="">
</div>
</div>
</body>
</html>