如何保持 iframe 的宽高比

Bro*_* KL 3 css iframe

我有一个带有以下 css 的 iframe:

.preview-iframe {
    width: 100%;
    height: 100%;
    border: 0;

    max-width: 1280px;
    max-height: 720px;
    margin: auto;
}
Run Code Online (Sandbox Code Playgroud)

它位于具有以下 CSS 的容器内:

.wrapper {
   position: absolute;
   width: calc(100% - 440px);
   height: 0;
   left: 0;
   top: 0;
   bottom: 0;
   text-align: center;
   background: #1c1c1c;
   display: flex;
   padding-bottom: 56.25%;
}
Run Code Online (Sandbox Code Playgroud)

包装器位于 div 内

position: fixed
Run Code Online (Sandbox Code Playgroud)

我试图在窗口大小调整时保持 iframe 的纵横比为 16:9,但上述方法不起作用。我应该怎么办?

sdv*_*ksv 5

<div class="wrapper">
  <iframe class="preview-iframe"> ... </iframe>
</div>

.wrapper {
  position: relative;
  height: 0;
  padding-bottom: 56.25%;
}
.preview-iframe {
  position: absolute;
  top: 0; left: 0;
  width: 100%;
  height: 100%;
}
Run Code Online (Sandbox Code Playgroud)


joe*_*joe 5

现在可以通过新的aspect-ratioCSS 属性实现这一点:

.element {
  width: 100px;
  aspect-ratio: 2 / 1;
  /* height will automatically be set to 50px */
}
Run Code Online (Sandbox Code Playgroud)

更多信息请参见:https ://css-tricks.com/almanac/properties/a/aspect-ratio/

它可在所有现代浏览器中使用