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

如何在固定宽高div中完整适配背景图:无裁切、不拉伸且占满宽度

背景图适配容器的解决方案

问题描述

需要将尺寸为318px 宽 × 422px 高的背景图完整放入290px × 310px的容器中,要求:

  • 不裁切图像内容
  • 图像不拉伸变形
  • 图像占满容器宽度

尝试background-size: cover;会裁切图像,background-size: contain;则会在容器内留下空白,均无法满足需求。

现有代码

.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  width: 290px;
  height: 542px;
  border-radius: 8px;
  border: 1px solid black;
}

.bg-img {
  background-image: url("url");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  height: 310px;
  border-radius: 8px 8px 0px 0px;
}
<div class="card">
    <div class="bg-img" />
</div>

解决方案

使用background-size: 100% auto;即可实现需求:

  • 100%强制图像宽度填满容器宽度
  • auto让图像高度按原始比例自动计算,保证图像不拉伸、完整显示

可根据视觉需求调整background-position,比如设置为top让图像顶部对齐容器,优化留白位置。

修改后的代码

.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  width: 290px;
  height: 542px;
  border-radius: 8px;
  border: 1px solid black;
}

.bg-img {
  background-image: url("url");
  background-size: 100% auto; /* 核心修改 */
  background-repeat: no-repeat;
  background-position: top; /* 可选调整对齐方式 */
  height: 310px;
  border-radius: 8px 8px 0px 0px;
}
<div class="card">
    <div class="bg-img"></div>
</div>

内容的提问来源于stack exchange,提问作者Hithesh kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:30:57