Otto Juul
Otto Juul

Reputation: 79

Responsive image

I'm trying to get responsive images to work for my header image.

<img srcset="/media/1501/here_header.jpg 960w, /media/1650/here_small.jpg 320w" sizes="(width: 960px)">

This is what I have so far, and it kind of works but when it gets larger than 960px the image keep getting larger, I want it to stop when it reaches 960px.

<img srcset="/media/1501/here_header.jpg 960w, /media/1650/here_small.jpg 320w" sizes="(max-width: 960px) 100vw">

What am I doing wrong?

Upvotes: 1

Views: 388

Answers (1)

Drew
Drew

Reputation: 3234

You can and should control the displayed width with CSS (i.e.: max-width: 960;), but you also should inform the browser the displayed size via the sizes attribute. The default of the sizes attribute is 100vw:

sizes="(max-width: 960px) 100vw" is transfered to sizes="(max-width: 960px) 100vw, 100vw", which basically means, if the viewport is lower 960px use the full viewport, otherwise use the full viewport, which doesn't make much sense. What you want is the following:

sizes="(max-width: 960px) 100vw, 960px"

You can also write: sizes="(min-width: 960px) 960px, 100vw" or as shorthand: sizes="(min-width: 960px) 960px"

<img srcset="/media/1501/here_header.jpg 960w, /media/1650/here_small.jpg 320w" sizes="(max-width: 960px) 100vw, 960px" style="max-width:960px;">

Upvotes: 2

Related Questions