【问题标题】:CSS vw and vh but relative to the parent instead of viewportCSS vw 和 vh 但相对于父级而不是视口
【发布时间】:2016-08-29 10:55:31
【问题描述】:

我正在尝试创建一个固定的纵横比框,它可以调整大小以不溢出其父级。

经典的padding-bottom trick 只能根据父级宽度定义高度,而可测试的here 允许元素随着宽度的增加而变得比父级更高。不好。

然而,使用 vh 和 vw,我们可以在父级是视口尺寸的限制下完成我们想要的。可测试here

<style>
  div {
    max-width: 90vw;
    max-height: 90vh;
    height: 50.625vw; /* height defined in terms of parent width (90*9/16) */
    width: 160vh; /* width defined in terms of parent height, which is missing from the padding-bottom trick (90*16/9) */
    background: linear-gradient(to right, gray, black, gray);
  }
</style>

<div></div>

有没有办法让 vh 和 vw 等价物引用父级而不是视口?或者对于解决其问题的填充底部技巧是否有一个补充技巧? css ratio 属性在哪里?

另外,images have some sort of intrinsic ratio,但我不确定如何利用这一点。

【问题讨论】:

  • 我不明白为什么填充技巧对你来说不够好?它是一个固定纵横比的盒子。你是说你想要与视口相同的比例,但在父级内?
  • 我希望盒子受到父母的高度和宽度的限制。在任一维度上,它都不应大于父级。

标签: html css


【解决方案1】:

您可以使用类似于我在 Maintain aspect ratio with a fixed height 中所做的事情,它利用了 &lt;canvas&gt; 元素的固有纵横比。

但是这里我们需要带有两个画布的嵌套容器。

#resize {
  resize: both;
  overflow: auto;
  width: 100px;
  height: 140px;
  padding: 20px;
  border: 1px solid black;
}
.ratio {
  position: relative;
  display: inline-block;
  vertical-align: middle;
}
.ratio.vertical, .ratio.vertical > canvas {
  height: 100%;
  max-width: 100%;
}
.ratio.horizontal, .ratio.horizontal > canvas {
  width: 100%;
  max-height: 100%;
}
.ratio > div {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
#contents {
  background: linear-gradient(to right, gray, black, gray);
}
<div id="resize">
  <div class="ratio vertical">
    <canvas width="16" height="9"></canvas>
    <div>
      <div class="ratio horizontal">
        <canvas width="16" height="9"></canvas>
        <div id="contents">
          Hello
        </div>
      </div>
    </div>
  </div>
</div>

【讨论】:

  • 啊,不能在 Chrome 上运行。我猜这个元素需要被强制重新渲染,但是resize 事件监听器只在窗口上工作。但请注意,当您加载窗口时,它会起作用,与 #resize 的大小无关
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-28
  • 2015-07-22
  • 1970-01-01
  • 2015-09-11
  • 1970-01-01
  • 1970-01-01
  • 2019-02-26
相关资源
最近更新 更多