很常见的需求

解法1

利用object-fit:contain方法处理,这个方法使用很简单 但是不兼容ie 在ie下默认填充100% 很不友好

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
<!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>
.box1,
.box2 {
width: 300px;
height: 300px;
border: 1px red solid;
margin: 10px auto;
}

img {
width: 100%;
height: 100%;
object-fit: contain;
}
</style>
</head>

<body>
<div class="box1"><img src="./1.jpg" alt=""></div>
<div class="box2"><img src="./2.jpg" alt=""></div>
</body>

</html>

解法2

更推荐的用法 对ie兼容好 样式不会发生变化

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
<!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>
.box1 {
background-image: url(./1.jpg);
}

.box2 {
background-image: url(./2.jpg);
}

.box1,
.box2 {
width: 300px;
height: 300px;
border: 1px red solid;
background-size: contain;
background-repeat: no-repeat;
background-position: center center;
margin: 10px auto;
}
</style>
</head>

<body>
<div class="box1"></div>
<div class="box2"></div>
</body>

</html>

示例

解法1示例
解法2示例