网页图片缩放的深入剖析

一、浏览器图片缩放默认表现行为行为

在想出解决方案之前,首先要弄清楚浏览器对于图片尺寸是怎么处理的,稍安勿躁,一步一步来分析下。
一个图片可以改变成任意尺寸,容器是80%:

<div>
  <img src="https://dummyimage.com/600x400/000/fff" alt="Norway">
</div>

不加任何属性:

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

图片默认是不会缩放的,宽高是图片原尺寸,图片宽高高于容器时会溢出。

width:100%

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

图片宽度随容器宽度缩放,图片宽高比不变,图片高度高于容器时会溢出。

max-width:100%

tips: max-height:100%效果是一样的

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

图片图片宽度随容器宽度缩放,图片宽高比不变,图片高度高于容器时会溢出,
但缩放不会超过原图宽高。

二、解决方案

1、图片容器宽度百分比,高度自适应;图片等比例自适应

还是上面那个例子,图片任意尺寸,容器是80%:

<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;
}

2、图片容器宽高百分比;图片等比例自适应

<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;
}

3、图片容器宽高百分比;图片居中覆盖不缩放(显示不完整但不失真)

<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;
}

4、使用picture元素或媒体查询,不同场景加载不同图片

如果<picture>元素与当前的<audio><video>元素协同合作将大大增强响应式图像的工作进程。它允许你放置多个source标签,以指定不同的图像文件名,进而根据不同的条件进行加载。

具体看:picturefill

    原文作者:识得唔识得啊
    原文地址: https://segmentfault.com/a/1190000009672757
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞