gpt4 book ai didi

css - 使用CSS在div上保持纵向纵横比

转载 作者:太空宇宙 更新时间:2023-11-04 07:01:43 24 4
gpt4 key购买 nike

给定:

.col-1 {width: 12.5%;}
.col-2 {width: 25%;}
.col-3 {width: 37.5%;}
.col-4 {width: 50%;}
.col-5 {width: 62.5%;}
.col-6 {width: 75%;}
.col-7 {width: 87.5%;}
.col-8 {width: 100%;}

我希望每个列的高度为其宽度的 150%。

我看过solutions for width to be calculated based on height that use the viewport's height - 但在这里引用视口(viewport)是不够的,因为一些列可能跨越屏幕的 1/8,而其他列可能跨越 1/4 等,而视口(viewport)高度将保持不变。

我看过 css calc() function proposed (例如,在列中的子 div 上)-但我不知道如何引用父元素的宽度。根据 W3Schools,% css 度量单位应该是相对于父元素的 - 但我想根据父元素宽度设置子高度,这是一种不同的度量。

W3Schools 还有一个 tutorial on maintaining aspect ratios通过将 padding-top 添加到包含的 div,作为百分比。例如,

padding-top: 66.66%;

将保持 3:2 的横向纵横比。但是如果我设置:

padding-top: 150%;

然后是的,我们获得了 2:3 的纵向比例,但是 100% 宽度的 div 的高度超过了窗口的高度。如果我试图通过将其宽度设置为以下来减小整个 div 的大小:

width: 25%;

然后列的宽度确实减小了,但它的高度仍然是屏幕高度的 150%。

关于使用 8 列布局并能够将 div 设置为 1 到 8 列的宽度并让浏览器自动将该 div 的高度设置为其宽度的 150%,有什么建议吗?

最佳答案

基于填充解决方案,类似这样的方法可行,但这样的标记非常丑陋,而且根据您要放入其中的内容,这可能是一件很糟糕的事情。

.col-1 {width: 12.5%;}
.col-2 {width: 25%;}
.col-3 {width: 37.5%;}
.col-4 {width: 50%;}
.col-5 {width: 62.5%;}
.col-6 {width: 75%;}
.col-7 {width: 87.5%;}
.col-8 {width: 100%;}

.height-ratio {
position: relative;
overflow: auto;
background: #ddd;
}

.height-ratio::before {
display: block;
width: 100%;
padding-top: 150%;
content: "";
}

.content {
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
padding: .25em;
}
<div class="col-1 height-ratio">
<div class="content">
some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing
</div>
</div>

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

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