為了讓IMG自適應大小,如下我做了一個橫向自適應的示例:
IMG樣式
(橫向拉伸,縱向自動匹配大?。?/p>
width:100%; height:auto;
(縱向拉伸,橫向自動匹配大小)
width:auto; height:100%;
DIV樣式(元素居中顯示)
display:flex; align-items:center; justify-content:center;
做法很簡單,只要設置對應圖片的width和htight的具體數值就可以了??聪旅娴睦樱?/p>
img{ width:auto; height:auto; max-width:100%; max-height:100%;}
這樣設置圖片的話,可以使圖片在指定的空間內縮放。4行的意思是:
示例代碼
如下是兩個大小和比例都不同的圖片,應用這個方法可以讓圖片自動填充并居中顯示
<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>
以上就是HTML如何讓IMG自動適應DIV容器大小的實現方法的詳細內容,更多關于HTML IMG自動適應DIV的資料請關注武林網其它相關文章!
新聞熱點
疑難解答