Image has correct aspect ratio on desktop browsers but wrong aspect ratio on mobile browsers

Viewed 65

I spent some hours isolating the bug. But I'd still like to understand it.

Below is the smallest amount of code I could replicate the bug into:

<div style='display: inline-flex;'>
    <img width=100% src='foo.jpg'>
</div>

I changed the image name and path to foo.jpg for the sake of the snippet, but everything else is exactly the same as what output the following.

Mobile:

Mobile Output

Desktop (mobile simulated):

enter image description here

Desktop (normal):

enter image description here

So, what's happening here? Am I doing something improper? Is there a "correct" way to write this snippet such that all browsers output it into the correct aspect ratio?

Update:

I've found a "solution" but I'm leaving this here as an unanswered question, because the solution is ugly. (Ugly code, anyway. The UI looks perfect.) All I need to do is wrap it in a div, like so:

<div style='display: inline-flex;'>
    <div>
        <img width=100% src='foo.jpg'>
    </div>
</div>

I hope a solution less ugly than this exists.

2 Answers

add either object-fit: contain; or object-fit: cover; to the image. containwill display the entire image. however you not allowed to set a height for the image then as it will be rezised automatically to contain the aspect ratio. cover allows to set a height and will cut the image to fit the container while maintaining the aspect ratio.

<div>
    <img style="object-fit: contain;" width="100%" src='https://www.tacoshy.de/Images/Yoshi/IMAG0735.jpg'>
</div>

sometimes chrome dev tools has some inaccuracies regarding its device simulations. That being said one reason your img might be squished on the actual mobile device is because you set the width to 100% and so it confined to 100% of the screens width (assuming its not wrapped by a container div that specifies a different size) whereas the height is not specified so it takes the space of its original size not 100% of its container.

Related