Niko Suominen
Niko Suominen

Reputation: 119

Image rendered size exceeds max-width

I have a responsive img tag:

<img width='800' height='600' srcset='img-400px.jpg 400w, img-700px.jpg 700w, img-1000px.jpg 1000w' sizes='(max-width: 1024px) 100vw, (max-width: 1840px) 63vw, 1200px' src='img.jpg'>

And CSS rules:

object-fit: contain;
width: auto;
margin: auto;
height: auto;
max-height: 900px;
max-width: 100%;

Even though the original image width is 800px and I have the rule max-width: 100% the browser renders the image wider than 800px. If I remove width: auto, the rendered size is correct (max 800px). Why does width: auto change the behaviour?

Upvotes: 1

Views: 1162

Answers (1)

Niko Suominen
Niko Suominen

Reputation: 119

I figured to understand what is the issue.

The browser does not override the max-width setting. When I use img with sizes attribute together with css rule width: auto, the browser uses sizes to allocate space for the image. This space can be wider than the image's real width. When I remove width: auto rule, the browser takes the width information from img's width attribute and the image can't exceed its intrinsic dimension. So the solution was to remove width: auto rule.

Upvotes: 0

Related Questions