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>