You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何拉伸placehold.co图片?为何设置宽高后无法实现拉伸?

问题:为何无法拉伸placehold.co的图片?

出于测试目的,我想要拉伸一张图片。以下是演示示例:

CSS 代码

div {
  width: 200px;
  height: 200px;
  border: 2px solid red;
}

img {
  display: block;
  width: 200px;
  height: 200px;
}

HTML 代码

<div>
  <img src="https://placehold.co/500x100" />
</div>

效果如下:
拉伸效果示意图

我的问题是:为何无法拉伸这张来自placehold.co的图片?


解答

这是因为CSS的object-fit属性默认值为contain,这个属性会让图片保持原始宽高比,同时适配你设置的width和height容器尺寸。所以即便你给img指定了200x200的宽高,图片只会按比例缩放,不会被强制拉伸填满整个红色边框的盒子。

如果要强制拉伸图片,让它完全填满设定的宽高,只需给img添加object-fit: fill;样式:

img {
  display: block;
  width: 200px;
  height: 200px;
  object-fit: fill;
}

添加后,图片就会忽略原始宽高比,被拉伸至200x200的尺寸。


内容的提问来源于stack exchange,提问作者Jeanluca Scaljeri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 13:52:38