Srcset And Viewport Width
I have 2 images: one desktop version, one mobile version. I would like the desktop image to be replaced by the mobile image when the viewport width resizes below 480px, just as wou
Solution 1:
It sounds like you want to do "art direction", i.e. the images are different more than just the smaller being scaled down version of the bigger image. If so, you need to use the picture
element.
<picture><sourcesrcset="http://placehold.it/300x150&text=mobile"media="(max-width: 480px)"><imgsrc="http://placehold.it/400x200&text=desktop"alt="..."></picture>
However, if your small image is actually a scaled-down version of the bigger image, then you can use srcset
, but then you have no control over which image gets chosen. It's up to the browser to pick the best one based on screen density, network conditions, user preference, browser cache, etc.
<imgsrc="http://placehold.it/400x200&text=desktop"srcset="http://placehold.it/400x200&text=desktop 400w,
http://placehold.it/300x150&text=mobile 300w"sizes="(max-width: 480px) 300px, 400px">
Note: If srcset
is used and the larger image candidate is in cache, Chrome will always display this cached image candidate - no matter of the actual viewport size.
Post a Comment for "Srcset And Viewport Width"