首页 > 解决方案 > 删除对象适合的填充:包含(图像缩放层)

问题描述

我将简要描述这个问题(我为 div 使用了不同的颜色):

这是我目前的布局情况:

现在的情况

当我垂直调整浏览器窗口大小时,会发生这种情况:

当前情况垂直调整大小

我的html代码是:

  <div class="wrap-container">         <!-- Yellow container-->
    <div class="wrap">                 <!-- Grey container-->
      <div class="image">              <!-- Aqua container-->
        <img src="images/me.png"/>     <!-- Red container-->
      </div>
   </div>
 </div>

我的CSS是:

.wrap-container{
  background-color: yellow;
}

.wrap{
  background: grey;
  display: flex;
  justify-content: flex-start;
}

.image-container{
  height: 100%;
  background: aqua;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;

  img{
    height: 80%;
    object-fit: contain;
    object-position: left;
    background: red;
    max-width: 368px; /* the original width of the image */
    max-height: 332px; /* the original height of the image */
 }
}

我希望水箱与图像一起缩放(所以永远不会看到红色),如下图所示:

所需的最终布局

提前致谢!:)

标签: javascripthtmlcsslayout

解决方案


Your provided code does not recreate your shown conditions, but the easiest way to achieve what you want is to change object-fit: contain; to object-fit: cover;

I've tried my best to recreate your conditions and made a few edits to simplify the controls.

The justify: flex-end on the image class has no benefit, and the height % values were working against you, so I've exchanged it for padding.

.wrap-container {
  background-color: yellow;
  display: flex;
  justify-content: center;
  width: 100%;
}

.wrap {
  background: grey;
  display: flex;
  width: 100%;
  max-width: 450px;
}

.image {
  background: aqua;
  padding-top: 10%;
  Width: 50%;
  display: flex;
  flex-direction: column;
}

img {
  background: red;
  object-fit: cover;
  object-position: center;
  max-height: 300px;
}
<div class="wrap-container">
  <!-- Yellow container-->
  <div class="wrap">
    <!-- Grey container-->
    <div class="image">
      <!-- Aqua container-->
      <img src="https://source.unsplash.com/random" />
      <!-- Red container-->
    </div>
  </div>
</div>


推荐阅读