gpt4 book ai didi

html - 使用 CSS 保持 div 的纵横比

转载 作者:bug小助手 更新时间:2023-10-28 10:52:45 26 4
gpt4 key购买 nike

我想创建一个 div,它可以随着窗口宽度的变化而改变其宽度/高度。

是否有任何 CSS3 规则允许高度根据宽度而变化,同时保持其纵横比

我知道我可以通过 JavaScript 做到这一点,但我更喜欢只使用 CSS。

div keeping aspect ratio according to width of window

最佳答案

只需创建一个包装器 <div> padding-bottom 的百分比值,像这样:

.demoWrapper {
padding: 10px;
background: white;
box-sizing: border-box;
resize: horizontal;
border: 1px dashed;
overflow: auto;
max-width: 100%;
height: calc(100vh - 16px);
}

div {
width: 100%;
padding-bottom: 75%;
background: gold; /** <-- For the demo **/
}
<div class="demoWrapper">
<div></div>
</div>

这将导致 <div>高度等于其容器宽度的 75%(纵横比为 4:3)。

这取决于填充的事实:

The percentage is calculated with respect to the width of the generated box's containing block [...] (source: w3.org, emphasis mine)

其他纵横比和 100% 宽度的底部填充值:

aspect ratio  | padding-bottom value
--------------|----------------------
16:9 | 56.25%
4:3 | 75%
3:2 | 66.66%
8:5 | 62.5%

在 div 中放置内容:

为了保持 div 的纵横比并防止其内容拉伸(stretch)它,您需要添加一个绝对定位的子元素并将其拉伸(stretch)到包装器的边缘:

div.stretchy-wrapper {
position: relative;
}

div.stretchy-wrapper > div {
position: absolute;
top: 0; bottom: 0; left: 0; right: 0;
}

Here's a demo还有一个更深入的demo

关于html - 使用 CSS 保持 div 的纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1495407/

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