gpt4 book ai didi

html - CSS vw 和 vh 但相对于父级而不是视口(viewport)

转载 作者:技术小花猫 更新时间:2023-10-29 12:55:24 25 4
gpt4 key购买 nike

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

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

然而,使用 vh 和 vw,我们可以在父级是视口(viewport)尺寸的限制下完成我们想要的。可测试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 等价物引用父对象而不是视口(viewport)?或者是否有解决其问题的 padding-bottom 技巧的补充技巧? css 比率属性在哪里?

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

最佳答案

您可以使用与我在 Maintain aspect ratio with a fixed height 中所做的类似的东西, 它利用了 <canvas> 的内在纵横比元素。

但是这里我们需要带有两个 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>

关于html - CSS vw 和 vh 但相对于父级而不是视口(viewport),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39197240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com