【问题标题】:Set a div height from its width (and vice versa) [duplicate]从宽度设置div高度(反之亦然)[重复]
【发布时间】:2022-01-23 00:59:55
【问题描述】:

我正在从事一个涉及创建不同标签的项目,这些标签具有不同的预定义格式。

有时标签的宽度优于其高度,反之亦然。

当宽度优越时,我想让 div 的宽度为父 div 的 90% 并相应地设置高度(通过保持相同的比例)。如果高度较高,反之亦然。

问题是因为我将宽度/高度设置为父 div 的百分比,我不知道如何保持比例。

我通过 twig 生成我的页面(我可以访问以毫米为单位的高度和宽度)。

这就是我现在正在做的事情。

{% if template.format.width >= template.format.height %}
    {% set templateWidth = 90 %}
    {% set templateHeight = (90/template.format.width)*template.format.height %}
{% else %}
    {% set templateWidth = (90/template.format.height)*template.format.width %}
    {% set templateHeight = 90 %}
{% endif %}

我的 div 是这样设置的:

style="position:relative; width: {{ templateWidth }}%; height: {{ templateHeight }}%"

我知道这是行不通的,因为父 div 的高度和宽度不同。

【问题讨论】:

    标签: html css twig


    【解决方案1】:

    您可以使用根变量:

    /* Assuming that your ratio is 4/5 */
    :root {
        --container-width: 90%;
        --container-height: calc(var(--container-width) * 4/5)
    }
    
    /* Now when you use these variables */
    #template {
        width: var(--container-width);
        height: var(--container-height);
    }
    

    【讨论】:

    • 我不知道这些,谢谢,我确实学到了一些东西!
    • Ofc!随时! :)
    • 这个答案是错误的。两个属性的百分比不会相同,因此这里没有比率。测试代码看看
    • 这在某些情况下可以工作。如果您保持变量不变,它将起作用:)
    【解决方案2】:

    您可以使用CSS aspect-ratio 来保持比率。

    width: {{ templateWidth }}%;
    height: {{ templateHeight }}%;
    aspect-ratio: {{ templateWidth }} / {{ templateHeight }};
    

    然后您可以修复widthheight 并将另一个设置为自动,例如:

    width: 100%;
    height: auto;
    

    或者反过来:

    width: auto;
    height: height;
    

    【讨论】:

    • 这正是我要找的!!
    猜你喜欢
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2013-07-08
    • 2012-06-07
    相关资源
    最近更新 更多