Responsive image using the srcset attribute
suggest changeUsing srcset with sizes
<img sizes="(min-width: 1200px) 580px,
(min-width: 640px) 48vw,
98vw"
srcset="img/hello-300.jpg 300w,
img/hello-600.jpg 600w,
img/hello-900.jpg 900w,
img/hello-1200.jpg 1200w"
src="img/hello-900.jpg" alt="hello">
sizes are like media queries, describing how much space the image takes of the viewport.
- if viewport is larger than 1200px, image is exactly 580px (for example our content is centered in container which is max 1200px wide. Image takes half of it minus margins).
- if viewport is between 640px and 1200px, image takes 48% of viewport (for example image scales with our page and takes half of viewport width minus margins).
- if the viewport is any other size, in our case less than 640px, the image takes 98% of the viewport (for example the image scales with the page and takes the full width of the viewport minus margins). The media condition must be omitted for the last item.
srcset tells the browser which images are available and what their sizes are.
img/hello-300.jpgis 300px wide,img/hello-600.jpgis 600px wide,img/hello-900.jpgis 900px wide,img/hello-1200.jpgis 1200px wide
src is always a mandatory image source. When srcset is also present, src is the fallback for browsers that do not support srcset.
Using srcset without sizes
<img src="img/hello-300.jpg" alt="hello"
srcset="img/hello-300.jpg 1x,
img/hello-600.jpg 2x,
img/hello-1200.jpg 3x">
srcset provides list of available images, with device-pixel ratio x descriptor.
- if device-pixel ratio is 1, use
img/hello-300.jpg - if device-pixel ratio is 2, use
img/hello-600.jpg - if device-pixel ratio is 3, use
img/hello-1200.jpg
src is always a mandatory image source. When srcset is also present, src is the fallback for browsers that do not support srcset.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents