如何将 (S)CSS 纵横比应用于不同尺寸的图像?

时间:2021-03-08 22:22:27

标签: html css sass

在我的一个页面布局中,我并排放置了卡片。每张卡片都有一个标题、一张图片和一个简短的描述。来自 QA 的某个人创建了一个异常值案例,并在混合中抛出了一张尺寸非常不规则的图像。无法说服老板修复生产中实际存在的一两个图像。相反,我现在需要想出一个会影响所有图像的解决方案。

这是简化的布局:

enter image description here

为简单起见,99.9% 的图片宽 300 像素,高 200 像素。

QA 会输入一张宽 1000 像素、高 1000 像素的图像。

以下在某些情况下有效:

@media screen and (max-width: 1024px) {
  .the-card-image {
    width: 100%;
    -o-object-fit: cover;
    object-fit: cover;
    -o-object-position: center;
    object-position: center;
    max-height: $btmimglgh;
    min-height: $btmimgsmh;
    max-width: $btmimglgw;
    min-width: $btmimgsmw;
  }
}

奇迹般地——在这个实际场景中——所有图像都具有相同的高度和宽度。 封闭容器(蓝色盒子)都没有任何设置的宽度或高度。它们的宽度基于百分比。

最大高度和最大宽度是图像可以获得的最高尺寸(通过 Inspector)。 min-height 和 min-width 是最小的尺寸。

但是,必须有更好的方法来做到这一点,对吗?

我已尝试在图像上定位:absolute; bottom: 0; left: 0; right: 0; top: 0; 无济于事。我必须支持旧版网络浏览器,因此无法使用 aspect-ratio(仍处于试验阶段)。

谁能想到一种“聪明的方法”来做到这一点——我显然无法弄清楚这一点。

.

1 个答案:

答案 0 :(得分:1)

这是我在评论中提到的 padding hack technique 的一个工作示例实现。

请注意,一张图片为 300x200,另一张为 1000x1000,但均符合 3x2 宽高比。后一个图像会根据需要在顶部和底部进行剪裁。

.image-container {
  /* establish positioning context for the img */
  position: relative;
  
  /* establish a 3x2 aspect ratio */
  height: 0;
  padding-top: 66.6666%;
  
  /* clip overflow */
  overflow: hidden;
}

.image-container > img {
  /* limit image to 100% width */
  max-width: 100%;
  
  /* pin to the container's bounds */
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  
  /* ensure it covers the available area, possibly
  some clipping if aspect ratio doesn't match */
  object-fit: cover;
}

/* the rest is purely cosmetic */

.container {
  display: flex;
  font-family: sans-serif;
}

.card {
  border-radius: 4px;
  width: 300px;
  box-shadow: 0 0 4px 2px rgba(0, 0, 0, 0.125);
  padding: 0.5rem 1rem 1rem;
  margin: 0.5rem;
}
<div class="container">
  <div class="card">
    <h3>300 x 200 Sollicitudin Magna</h3>
    <div class="image-container">
      <img src="//placekitten.com/300/200" />
    </div>
    <p>
      Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Nullam quis risus eget urna mollis ornare vel eu leo.
    </p>
  </div>

  <div class="card">
    <h3>1000 x 1000 Sollicitudin Magna</h3>
    <div class="image-container">
      <img src="//placekitten.com/1000/1000" />
    </div>
    <p>
      Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Nullam quis risus eget urna mollis ornare vel eu leo.
    </p>
  </div>
</div>