Thomas
Thomas

Reputation: 95

img's sizes attribute scales images up, doesn't obey max-width

I'm trying to implement responsive images for content images (images within articles), the img/srcset/sizes way. I have a responsive site with a single column layout for mobile and tablet with images stretching to 100%. I use a max-width: 100%; height: auto; in CSS and would expect the images to not exceed their original dimensions.

However, in my images' sizes attribute I've defined a default size of 100vw for mobile and tablet. This works for images whose largest version has a width larger than what turns out to be 100vw. However this pumps up smaller images, whose original size is smaller than the 100vw, so that they become really ugly.

I thought max-width: 100%; on images would prevent them from scaling up larger than they should be. And I understood the sizes attribute as a way of telling the browser in which size the image is going to be displayed, but did not expect it to scale the image - or at least obey to added CSS rules.

I have the same behavior in Chrome and Firefox... so I'm not sure if this is related to this issue

BTW: The sizes attribute is set programmatically in an import script, so large and small images are treated the same way.

Any idea what I'm doing or understanding wrong. Any help is appreciated! Thanks!

Upvotes: 2

Views: 694

Answers (2)

Ismael Miguel
Ismael Miguel

Reputation: 4241

You misunderstood the concept.

max-width only limits the width based on the parent container.

You can easily see the effect here:

<img src="http://placehold.it/300x150.png" width="500" style="max-width:100%;">
    
<div style="max-width:50%;">
    <img src="http://placehold.it/300x150.png" width="1000" style="max-width:100%;">
</div>

If you want to limit the image size, wrap it in a div.

Then, on that div, you set the width you wish.

The images will scale up to that width.

Basically, just like how I did with the <div>.

Upvotes: 2

Nathan
Nathan

Reputation: 77

It's a bit of a guess, but have you tried adding width:auto; before max-width:100%?

Upvotes: -1

Related Questions