Home > other >  Set a div height from its width (and vice versa)
Set a div height from its width (and vice versa)

Time:12-22

I am working on a project that involves creating different labels, these labels have different predefined formats.

Sometimes the width of the label is superior that its height and vice versa.

When the width is superior, I would like to make the div's width 90% of the parent div and set the height accordingly (by keeping the same ratio). Vice versa if the height is superior.

The thing is since I set my width/height in percentage of the parent div, I don't know how to keep the ratio.

I generate my page through twig (I have access to both the height and width in millimeters).

This is what I am doing right now.

{% 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 %}

My div is set like this :

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

I know this can't work since the parent div does not have the same height and width.

CodePudding user response:

You can use root variables:

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

CodePudding user response:

You can use CSS aspect-ratio to maintain the ratio.

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

Then you can fix either the width or the height and set the other one to auto, for example:

width: 100%;
height: auto;

or vice-versa:

width: auto;
height: height;
  • Related