I just copied your code and placed it into a snippet and it seems to be working correctly?
If I was you I would ensure that no other styles are overwriting what you have shared in your question.
.div1 {
position: absolute;
top: 20px;
left: 20px;
height: 100px;
width: 100px;
display: flex;
align-items: center;
justify-content: center;
}
.div2 {
position: relative
max-width: 100%;
max-height: 100%;
object-fit: contain;
border: 3px red solid;
}
.div2 img {
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
margin: auto;
}
<div class="div1">
<div class="div2">
<img src="https://via.placeholder.com/150">
</div>
</div>
I have div1, div2 and an image with the following structure:
<div1>
<div2>
<img>
</div2>
</div1>
div1:
position: absolute;
top, width, height: somevalue;
display: flex;
align-items: center;
justify-content: center;
div2:
position: relative
max-width: 100%;
max-height: 100%;
object-fit: contain;
border: 3px red solid;
& img {
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
margin: auto;
}
However the large image still exceeds div1
. I have tried putting display:contents
in div2 which works fine, but I need extra image siblings position absolute to the first image, which doesn’t work with display:content
(sort of mistakenly positioning absolute to div1).
If I put display:absolute
inside img
then I can’t see the image, there is only a red dot(come from div2 border) in the center.
Let’s forget about the image siblings, why the main displaying image still exceed div2’s maximum size?