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

时间:2017-06-22 17:58:12

标签: css image background-image

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

2 个答案:

答案 0 :(得分:1)

如果您使用img元素,则已经回答过: Is there an equivalent to background-size: cover and contain for image elements?

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

答案 1 :(得分:0)

可能有更好的方法可以做到这一点,但这就是我通常从这开始。

具有固定尺寸的父div。然后,我将该图片添加为该父background内的div个孩子div

图像总是调整并适合父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>