从其宽度设置div高度(反之亦然)



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

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

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

问题是,由于我以父div的百分比设置了宽度/高度,我不知道如何保持这个比率。

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

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

{% 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没有相同的高度和宽度。

您可以使用CSSaspect-ratio来维护比率。

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

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

width: 100%;
height: auto;

或者反过来:

width: auto;
height: height;

您可以使用根变量:

/* 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);
}

最新更新