How to get div height to auto-adjust to background size?

Problem: when we set a background image on div the div size doesn’t adjust to background image size.

Solution:

height: calc(imageRatio * 100vw);

Explanation:

First, we need to get the ratio from the background image. We simply divide one dimension by another. Then we get something like for example 66.4%

When we have image ratio we can simply calculate the height of the div by multiplying the ratio by viewport width: calc(0.664 * 100vw)

A height of a div is automatically updated when the window is resized.

See also: my answer on StackOverflow – https://stackoverflow.com/a/61990449/3775079

Leave a Reply

Your email address will not be published. Required fields are marked *