IMG样式
(横向拉伸,纵向自动匹配大小)
width:100%; height:auto;
(纵向拉伸,横向自动匹配大小)
width:auto; height:100%;
DIV样式(元素居中显示)
display:flex; align-items:center; justify-content:center;
示例代码
如下是两个大小和比例都不同的图片,应用这个方法可以让图片自动填充并居中显示
<html> <head> <title>让图片自动适应DIV容器大小</title> <style> .ShaShiDi{ width:500px; height:400px; display:flex; align-items:center; justify-content:center; /*为了效果明显,可以将如下边框打开,看一下效果*/ /* border:1px solid black; */ } .ShaShiDi img{ width:100%; height:auto; } </style> </head> <body> <div class="ShaShiDi"> <img src="./1.png"/> </div> <div class="ShaShiDi"> <img src="./2.png"/> </div> </body> </html>