An Image in HTML is a replaced element
If you inspect the img in your developer tools, you might recognize that the image element itself covers all of the parent (that's by means of width: 100%; height: 100%;
).
The representation of the image on screen is altered by object-fit: contain;
. But this does not change the dimensions of the image element itself. You can see that if I add a yellow background to the image element. This covers all of the blue parent
let parent = document.getElementById("parent");
let img = document.getElementById("img");
parent.addEventListener("click", function() {
parent.style.display = "none";
});
img.addEventListener("click", function(e) {
e.stopPropagation();
})
#parent {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background-color: blue;
}
#img {
width: 100%;
height: 100%;
object-fit: contain;
background: yellow;
}
<div id="parent">
<img src="https://dummyimage.com/600x400/000/fff" id="img">
</div>
You need to try something different for your code to work as intended
Edit: changed the implementation
Example with image size 500 x 500
let parent = document.getElementById("parent");
let img = document.getElementById("img");
parent.addEventListener("click", function() {
parent.style.display = "none";
});
img.addEventListener("click", function(e) {
e.stopPropagation();
})
#parent {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background-color: blue;
}
#img {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
max-width: 100%;
max-height: 100%;
margin: auto;
}
<div id="parent">
<img src="https://dummyimage.com/500x500/f0f/000" id="img">
</div>
Example with image size 1000 x 600
let parent = document.getElementById("parent");
let img = document.getElementById("img");
parent.addEventListener("click", function() {
parent.style.display = "none";
});
img.addEventListener("click", function(e) {
e.stopPropagation();
})
#parent {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background-color: blue;
}
#img {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
max-width: 100%;
max-height: 100%;
margin: auto;
}
<div id="parent">
<img src="https://dummyimage.com/1000x600/f0f/000" id="img">
</div>
Example with image size 600 x 1000
let parent = document.getElementById("parent");
let img = document.getElementById("img");
parent.addEventListener("click", function() {
parent.style.display = "none";
});
img.addEventListener("click", function(e) {
e.stopPropagation();
})
#parent {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background-color: blue;
}
#img {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
max-width: 100%;
max-height: 100%;
margin: auto;
}
<div id="parent">
<img src="https://dummyimage.com/600x1000/f0f/000" id="img">
</div>