网页图片缩放的深入剖析

本文详细介绍了如何使图片在网页中实现自适应及缩放功能,包括使用max-width和max-height属性来确保图片在不同容器尺寸下保持原始宽高比的同时能够正确显示,并通过设置min-height和max-height来限定图片展示的高度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

图片缩放问题困扰我许久了,贼鸡儿烦,今天彻底解决这个东西。

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值