Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading