I have an application where I fetch an image and its size from a JSON. My issue is that when the image is loading, there is a gap left behind that I would like to fill.
The problem arises when I try to use a div
with fixed width
and height
to fill this gap. It ends up not being responsive if the image has styles like height: auto; max-height: XXXpx;
. So, how can I maintain responsiveness without compromising the width / height proportion?
NOTE: I want this solution to work for any width and height combination while still preserving the ratio / proportion.
UPDATE:
Let me illustrate my problem with an example. As you can see, the div
has a fixed size which causes overflow when the window width or height is less than 256px
, even though the image remains responsive. So, how do I make the div
responsive without losing this proportion?
<html>
<head></head>
<body>
<!--
This div contains the image and by default uses the `container` class (explained below) with a fixed width and height matching the image size.
This class will be removed once the image loads to make it "responsive".
-->
<div
id="container"
class="container"
>
<!--
The image utilizes the `image` class with necessary responsive styles, and triggers "removeDummyClass()" on load.
-->
<img
class="image"
src="https://sftextures.com/texture/2574/0/2578/dog-foot-pad-on-white-snow-frozen-ground-dark-footprint-sign-icy-cold-winter-pattern-seamless-texture-256x256.jpg"
onload="removeDummyClass()"
/>
</div>
<script type="text/javascript">
// Function to remove class with a dummy image (background-color in this case)
const removeDummyClass = () => {
document
.getElementById('container')
.classList
.remove('container')
}
</script>
<style>
.container {
background-color: red;
width: 256px;
height: 256px;
}
.image {
height: auto;
max-width: 100%;
}
</style>
</body>
</html>
UPDATE 2:
To better illustrate the issue, I am including some screenshots, not for debugging purposes, but to clarify the problem.
Initially, the div overflows due to manually set width and height.
https://i.sstatic.net/j1Dtt.png
Once the image loads, it resizes without losing the width-to-height proportion.