首页 > 解决方案 > 使用css在div上保持纵向纵横比

问题描述

鉴于:

.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%;}

我希望每个 col 的高度是其宽度的 150%。

我已经看到了基于使用视口高度的高度计算宽度的解决方案- 但在这里引用视口是不够的,因为有些列可能跨越屏幕的 1/8,而其他列可能跨越 1/4 等,而视口高度将是恒定的。

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

W3Schools 还有一个关于通过将 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% 的任何建议?

标签: cssdependenciesheightwidthaspect-ratio

解决方案


基于填充解决方案,这样的事情可能会起作用,但这在标记方面非常难看,并且根据您想要放入其中的内容,这可能是一件糟糕的事情。

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


推荐阅读