在想出解決方案以前,首先要弄清楚瀏覽器對於圖片尺寸是怎麼處理的,稍安勿躁,一步一步來分析下。
一個圖片能夠改變成任意尺寸,容器是80%:html
<div> <img src="https://dummyimage.com/600x400/000/fff" alt="Norway"> </div>
img {} div{ width:80%; background-color:pink; text-align: center; }
圖片默認是不會縮放的,寬高是圖片原尺寸,圖片寬高高於容器時會溢出。git
img { width:100%; } div{ width:80%; background-color:pink; text-align: center; }
圖片寬度隨容器寬度縮放,圖片寬高比不變,圖片高度高於容器時會溢出。github
tips: max-height:100%效果是同樣的瀏覽器
img { max-width:100%; } div{ width:80%; background-color:pink; text-align: center; }
圖片圖片寬度隨容器寬度縮放,圖片寬高比不變,圖片高度高於容器時會溢出,
但縮放不會超過原圖寬高。app
仍是上面那個例子,圖片任意尺寸,容器是80%:ide
<div> <img src="https://dummyimage.com/600x400/000/fff" alt="Norway"> </div>
img { max-width: 100%; /* max-height: 400px; */ } div{ width:80%; /* min-height: 300px; */ background-color:pink; text-align: center; }
img { max-width: 100%; max-height: 400px; } div{ width:80%; /* min-height: 300px; */ background-color:pink; text-align: center; }
tips:此時若圖片小於最小高度,圖片垂直居中(採用flex佈局)佈局
img { max-width: 100%; /* max-height: 400px; */ } div{ width:80%; min-height: 300px; background-color:pink; display: flex; justify-content: center; align-items: center; }
img { max-width: 100%; max-height: 400px; } div{ width:80%; min-height: 300px; background-color:pink; display: flex; justify-content: center; align-items: center; }
<html> <head></head> <body> <div class='wrapper'> <div class='image'></div> </div> </body> </html>
html,body{ height: 100%; } .wrapper{ width:80%; height:80%; background-color: pink; } .image{ width: 100%; height: 100%; background-image: url('https://dummyimage.com/600x400/000/fff'); background-size: contain; background-position: center center; background-repeat: no-repeat; background-color: #aaa; }
<html> <head></head> <body> <div class='wrapper'> <div class='image'></div> </div> </body> </html>
html,body{ height: 100%; } .wrapper{ width:80%; height:80%; background-color: pink; } .image{ width: 100%; height: 100%; background-image: url('https://dummyimage.com/600x400/000/fff'); background-size: cover; background-position: center center; }
若是<picture>
元素與當前的<audio>
和<video>
元素協同合做將大大加強響應式圖像的工做進程。它容許你放置多個source標籤,以指定不一樣的圖像文件名,進而根據不一樣的條件進行加載。flex
具體看:picturefillurl