HTML中使用css如何让IMG自动适应DIV容器大小,实现不变形、最大化展示图片。
<!DOCTYPE html>
<html lang="en">
<head>
<title>IMG自动适应</title>
<style>
/* init默认样式 */
* {
padding: 0;
margin: 0;
}
/* 设置外部盒子宽、高 */
div {
margin-left: 200px;
width: 150px;
height: 300px;
background: rgb(248, 206, 114);
display: flex;
justify-content: center;
align-items: center;
}
p {
margin-left: 200px;
width: 300px;
height: 300px;
background: rgb(131, 241, 121);
display: flex;
justify-content: center;
align-items: center;
}
/* 设置图片标签最大宽、最大高 ,按比例最大尺寸显示*/
img {
max-width: 100%;
max-height: 100%;
}
</style>
</head>
<body>
<div>
<img
src="https://img0.baidu.com/it/u=1190923370,21511699&fm=26&fmt=auto&gp=0.jpg"
alt=""
/>
</div>
<p>
<img
src="https://img0.baidu.com/it/u=1190923370,21511699&fm=26&fmt=auto&gp=0.jpg"
alt=""
/>
</p>
</body>
</html>
如图:
![](https://img.haomeiwen.com/i25378018/8c71c7096f7c13fa.png)
self_adapting.png
网友评论