简体   繁体   English

CSS vw和vh但相对于父而不是视口

[英]CSS vw and vh but relative to the parent instead of viewport

I'm trying to create a fixed aspect ratio box that resizes to not overflow its parent. 我正在尝试创建一个固定的宽高比框,调整大小以不溢出其父级。

The classic padding-bottom trick is only able to define height in terms of parent width, and as testable here allows the element to grow taller than the parent as width increases. 经典的padding-bottom技巧只能根据父宽度定义高度,并且这里可测试允许元素在宽度增加时比父元素更高。 Not good. 不好。

Using vh and vw however, we can accomplish what we want with the restriction that the parent is the dimensions of the viewport. 然而,使用vh和vw,我们可以通过父视图是视口的尺寸的限制来实现我们想要的。 Testable 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>

Is there a way to have a vh and vw equivalent that references the parent instead of the viewport? 有没有办法让vh和vw等效引用父而不是视口? Or is there a complimentary trick to the padding-bottom trick which fixes its problems? 或者是否有一个补充技巧来解决其问题? Where is the css ratio property? css比率属性在哪里?

Also, images have some sort of intrinsic ratio , but I'm unsure how to take advantage of this. 此外, 图像具有某种内在比例 ,但我不确定如何利用这一点。

You can use something similar to what I did in Maintain aspect ratio with a fixed height , which takes advantage the intrinsic aspect ratio of <canvas> elements. 你可以使用类似于我在保持纵横比和固定高度时所做的事情,这利用了<canvas>元素的内在纵横比。

But here we need nested containers with two canvas. 但是在这里我们需要带有两个画布的嵌套容器。

 #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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM