图片比例和外部div比例不一致,最大程度占满,并且图片比例不变
其中1.jpg
,2.jpg
,1.html
在同一目录
|-----
|- 1.jpg
|- 2.jpg
|- 1.html
1.jpg
2.jpg
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.image-container {
width: 600px;
height: 600px;
display: flex;
justify-content: center;
align-items: center;
}
.image-container img {
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
object-fit: contain;
}
</style>
</head>
<body>
<div style="width: 600px; height: 600px">
<div class="image-container">
<img src="./1.jpg" alt="Example image" />
</div>
</div>
<div style="width: 600px; height: 600px">
<div class="image-container">
<img src="./2.jpg" alt="Example image" />
</div>
</div>
</body>
</html>
示例2,上面写法如果图片小于div会上下左右都有白
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.image-container {
width: 600px;
height: 600px;
display: flex;
justify-content: center;
align-items: center;
background-color: #f0f0f0; /* 添加背景色以便观察留白 */
}
.image-container img {
object-fit: contain; /* 保持比例,确保整个图片可见 */
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div style="width: 600px; height: 600px">
<div class="image-container">
<img src="./3.jpg" alt="Example image" />
</div>
</div>
<div style="width: 600px; height: 600px">
<div class="image-container">
<img src="./1.jpg" alt="Example image" />
</div>
</div>
<div style="width: 600px; height: 600px">
<div class="image-container">
<img src="./2.jpg" alt="Example image" />
</div>
</div>
</body>
</html>
效果图