如何讓img自動適應div容器大小


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>



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM