如何使用 CSS 保持 16:9 和 4:3 之间的纵横比?

How to maintain aspect ratio between 16:9 and 4:3 using CSS?

目标是渲染一个没有信箱的对象,只要宽高比在给定的范围内,例如在 16:9 和 4:3 之间。

例如,当 16:9 图像的可用宽度缩小到低于 16:9 宽高比时,我们想要裁剪图像的左侧和右侧。如果宽度进一步减小到 4:3 纵横比以下,我们希望保持该纵横比并开始缩小。

在此示例中,您可以看到对象如何缩放。这种方法的问题在于,一旦可用 space 甚至相差一个像素,缩放就会立即发生。

.iframe {
  border: 1px solid black;
  width: 350px;
  height: 350px;
  resize: both;
  overflow: auto;
}

.wrapper {
  background-color: #c05046;
  height: 100%;
  display: flex;
}

.image {
  margin: 0 auto;
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
<div class="iframe">
  <div class="wrapper">
      <img class="image" src="https://i.ytimg.com/vi/PX-0Nrg4Yhw/maxresdefault.jpg">
  </div>
</div>

[示例中模拟了一个 iframe,您可以更改其大小以更改可用 space。]

https://voormedia.com/blog/2012/11/responsive-background-images-with-fixed-or-fluid-aspect-ratios 中解释的流体比率技巧可以以某种方式实现 2 个比率之间的缩放,但有几个缺点:

.iframe {
  background-color: #c05046;
  border: 1px solid black;
  width: 350px;
  height: 350px;
  resize: both;
  overflow: auto;
}

.column {
  max-width: 640px;
}

figure.fluidratio {
  margin: 0;
  padding-top: 15%; /* slope */
  height: 240px; /* start height */
  background-image: url(https://i.ytimg.com/vi/PX-0Nrg4Yhw/maxresdefault.jpg);
  background-size: cover;
  -moz-background-size: cover; /* Firefox 3.6 */
  background-position: center; /* Internet Explorer 7/8 */
}
<div class="iframe">
  <div class="column">
    <figure class="fluidratio"></figure>
  </div>
</div>

我看到有人建议使用嵌入式 SVG,但没有让这些示例起作用。

感谢任何反馈。

如果我对问题的理解正确,你想实现这样的目标:

      .iframe {
        border: 1px solid black;
        width: 100%;
        height: 100%;
      }

      .container {
        width: 100%;
        max-width: 130vh;
        position: relative;
        margin: 0 auto;
      }

      .wrapper {
        background-color: #c05046;
        height: 0;
        padding-top: 75%;
        position: relative;
        width: 75%;
        left: 50%;
        transform: translateX(-50%);
        max-width: 640px;
      }

      .image {
        position: absolute;
        top: 0;
        left: 50%;
        transform: translateX(-50%);
        height: 100%;
      }
    <div class="iframe">
      <div class="container">
      <div class="wrapper">
          <img class="image" src="https://i.ytimg.com/vi/PX-0Nrg4Yhw/maxresdefault.jpg">
      </div>
      </div>
    </div>

*此处禁用调整大小,请在响应模式下全屏查看。

使用内部.wrapper,它保持比例为4/3的部分始终可见,但它允许内容溢出它的边界。通过 max-height: 130vh 它的高度也不断缩放。由于它不基于背景图像,因此它可以用于视频和图像。

主要缺点是使用 vh 单位使其相对于视图端口大小、父容器高度。 -> 查看评论