提问者:小点点

使用CSS Object-Fit:contain on image在其周围留下空格


我有一个容器image-wrapper和其中的一个图像。

容器具有固定的高度和宽度。在它内部,图像分辨率将是动态的。

我所要做的就是将图像水平和垂直地居中到容器中,并对其应用一些框影样式。

但它在图像周围留下了一个空白,看起来很怪异。下面是代码。垂直图像也是如此。

null

.image-wrapper {
  height: 400px;
  width: 400px;
  background-color: rgb(0,200,100);
  padding: 40px;
}

.image-wrapper img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  box-shadow: 10px 10px 10px red;
}
<div class="image-wrapper">
  <img src="https://via.placeholder.com/500x200">
</div>

null

我只想在图像周围有一个阴影,没有空间。我想我错过了一件很简单的事情。

我已经尝试将position:relative添加到容器中,但没有起作用。

我试图通过搜索“CSS对象适合图像阴影”,“CSS对象适合图像添加空间”之类的东西来搜索它,但没有找到任何类似的东西。


共1个答案

匿名用户

我的解决方案没有裁剪和使用Flexbox:

null

.image-wrapper {
  height: 100%;
  width: 500px;
  background-color: rgb(0,200,100);
  padding: 40px;
  display : flex;
  justify-content: center;
  align-items: center;
}

.image-wrapper img {
  width: 100%;
  object-fit: contain;
  box-shadow: 10px 10px 10px red;
}
<div class="image-wrapper">
  <img src="https://via.placeholder.com/500x1000">
</div>