網頁圖片縮放的深刻剖析

1、瀏覽器圖片縮放默認表現行爲行爲

在想出解決方案以前,首先要弄清楚瀏覽器對於圖片尺寸是怎麼處理的,稍安勿躁,一步一步來分析下。
一個圖片能夠改變成任意尺寸,容器是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

width:100%

img {
  width:100%;
}
div{
  width:80%;
  background-color:pink;
  text-align: center;
}

圖片寬度隨容器寬度縮放,圖片寬高比不變,圖片高度高於容器時會溢出。github

max-width:100%

tips: max-height:100%效果是同樣的瀏覽器

img {
  max-width:100%;
}
div{
  width:80%;
  background-color:pink;
  text-align: center;
}

圖片圖片寬度隨容器寬度縮放,圖片寬高比不變,圖片高度高於容器時會溢出,
但縮放不會超過原圖寬高。app

2、解決方案

一、圖片容器寬度百分比,高度自適應;圖片等比例自適應

仍是上面那個例子,圖片任意尺寸,容器是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元素或媒體查詢,不一樣場景加載不一樣圖片

若是<picture>元素與當前的<audio><video>元素協同合做將大大加強響應式圖像的工做進程。它容許你放置多個source標籤,以指定不一樣的圖像文件名,進而根據不一樣的條件進行加載。flex

具體看:picturefillurl

相關文章
相關標籤/搜索