如何使用 CSS 将图像调整为自身的百分比?

新手上路,请多包涵

我正在尝试使用自身的百分比调整图像的大小。例如,我只想通过将图像大小调整为 50% 来将图像缩小一半。但是应用 width: 50%; 会将图像的大小调整为容器元素的 50%(例如 <body> 的父元素)。

问题是,我可以在不使用 JavaScript 或服务器端的情况下根据自身的百分比调整图像大小吗? (我没有图像大小的直接信息)

我很确定你不能这样做,但我只是想看看是否有智能 CSS 解决方案。谢谢!

原文由 Min Ming Lo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 665
2 个回答

我有两种方法给你。

方法一。

此方法仅调整图像的视觉尺寸而不是 DOM 中的实际尺寸,并且调整尺寸后的视觉状态居中于原始尺寸的中间。

 img {
  transform: scale(0.5);
}
 <img src="https://via.placeholder.com/300x200" />

浏览器支持说明: 浏览器统计信息显示在 css 中。

方法二。

 #wrap {
  overflow: hidden;
  position: relative;
  float: left;
}

#wrap img.fake {
  float: left;
  visibility: hidden;
  width: auto;
}

#img_wrap {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

#img_wrap img.normal {
  width: 50%;
}
 <div id="wrap">
  <img class="fake" src="https://via.placeholder.com/300x200" />

  <div id="img_wrap">
    <img class="normal" src="https://via.placeholder.com/300x200/cccccc" />
  </div>
</div>

注意: img.normalimg.fake 是同一张图片。

浏览器支持说明: 此方法适用于所有浏览器,因为所有浏览器都支持 css 方法中使用的属性。

该方法以这种方式工作:

  1. #wrap#wrap img.fake 有流量
  2. #wrapoverflow: hidden 因此它的尺寸与内部图像相同( img.fake
  3. img.fake 是里面唯一的元素 #wrap 没有 absolute 定位,这样它就不会破坏第二步
  4. #img_wrap has absolute positioning inside #wrap and extends in size to the entire element ( #wrap )
  5. 第四步的结果是 #img_wrap 与图像具有相同的尺寸。
  6. By setting width: 50% on img.normal , its size is 50% of #img_wrap , and therefore 50% of the original image尺寸。

原文由 Vladimir Starkov 发布,翻译遵循 CC BY-SA 4.0 许可协议

这一定是使用容器元素方法的最简单的解决方案之一。

使用容器元素方法时,此问题是 问题的变体。诀窍是让容器元素收缩包装子图像,因此它的大小将等于未调整大小的图像的大小。因此,当将图像的 width 属性设置为百分比值时,图像将相对于其原始比例进行缩放。

其他一些启用收缩包装的属性和属性值是: float: left/rightposition: fixedmin/max-width ,56–如问题中所述。每个都有自己的副作用,但 display: inline-block 将是一个更安全的选择。马特在他的回答中提到了 float: left/right ,但他错误地将其归因于 overflow: hidden

 span {
  display: inline-block;
}

img {
  width: 50%;
}
 <span>
        <img src="https://via.placeholder.com/300x200"/>
    </span>

编辑: 正如 trojan 所提到的,您还可以利用新引入的 CSS3 intrinsic & extrinsic sizing 模块

 figure {
  width: intrinsic;
}

img {
  width: 50%;
}
 <figure>
  <img src="https://via.placeholder.com/300x200" />
</figure>

但是, 在撰写本文时,并非所有流行的浏览器版本都支持它

原文由 user3829636 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题