小 div 内有大图,没有裁剪或纵横比变化

Large image inside small div with no cropping or change in aspect ratio

我有一个 div 宽度为 30% 并包含背景图像。图片本身约为 500px x 300px。当浏览器足够宽时,30% 宽 div 约为 500px,整个图像显示效果很好,没有裁剪或拉伸。但是当视口很窄并且 div 缩小到 300px 时,500px 的图像正在被裁剪。有没有办法拍摄大图像并将其强制放入较小的容器中而不会裁剪且不会损失纵横比?如果不是,什么是使图像填满 div 且在我切换图像的媒体查询断点之间不裁剪或丢失纵横比的正确方法?

如果您使用的是 img 元素,则此问题已得到解答: Is there an equivalent to background-size: cover and contain for image elements?

但如果您想坚持使用 CSS 并使用 background-image:url('...'); 只需将 background-size 设置为 background-size: contain;.

也许有更好的方法来做到这一点,但这是 我通常从这里开始的。

具有固定尺寸的父项 div。然后,我将图像添加为该父项 div 中子项 divbackground

图像总是调整并适合父级 div。

.my-image-parent {
  display: inline-block;
  width: 300px;
  height: 300px;
  background: #131418; /* for demo only */
  line-height: 300px; /* should match your div height */
  text-align: center;
  font-size: 0;
}


/* demonstration backgrounds */
.bg1 {background: url(https://unsplash.it/300/300);}
.bg2 {background: url(https://unsplash.it/800/800);}
.bg3 {background: url(https://unsplash.it/1920/1080);}
.bg4 {background: url(https://unsplash.it/760/1240);}

.my-image {
  width: auto;
  height: 100%;
  vertical-align: middle;
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
}
<div class="my-image-parent">
  <div class="my-image bg1"></div>
</div>

<div class="my-image-parent">
  <div class="my-image bg2"></div>
</div>

<div class="my-image-parent">
  <div class="my-image bg3"></div>
</div>

<div class="my-image-parent">
  <div class="my-image bg4"></div>
</div>