Responsive images and art direction
— Updated
Responsive images are often implemented using the srcset
attribute. The srcset
attribute is a comma-separated list of image filenames and their width or density descriptors. To prevent layout shifts, set the width
and height
attributes on <img>
and <source>
tags that use srcset
.
For responsive images that use density descriptors:
- All images listed in
src
andsrcset
should have the same aspect ratio. - Set the
width
andheight
attributes to match the dimensions of the1x
image. - The
src
attribute should refer to the1x
image.
For responsive images that use width descriptors:
- All images listed in
src
andsrcset
should have the same aspect ratio. - Set the
width
andheight
attributes to match the dimensions of the fallback image. - Adjust image styling as needed: In the absence of any CSS styling, setting
width
andheight
on a responsive image that uses width descriptors will cause the image to always render at the same size - even if the images listed insrcset
have varying dimensions. This behavior may not be what you want. Addingwidth: 100%; height: auto;
orwidth: 100vw; height: auto;
to your image styling may give you the visual appearance you want.
For <picture> tags:
- Set the
width
andheight
attributes for all<source>
tags: The appropriate values forwidth
andheight
will depend on how the<source>
tag usessrcset
. (See above for information on working withsrcset
.) - Adjust image styling: If you need to adjust image styling, keep in mind that adding styling to a
<source>
tag will have no effect - a<source>
tag is an empty element. Instead, you will need to style the corresponding<img>
tag. - Set the
width
andheight
attributes on the<img>
tag: These values should match the intrinsic size of the fallback image.
<!-- Using density descriptors -->
<img width="480" height="330"
srcset="cat-1x.jpg, cat-2x.jpg 2x, cat-3x.jpg 3x"
src="cat-1x.jpg"
alt="Photo of a cat on a green background">
<!-- Using width descriptors -->
<img width="256" height="128"
srcset="dog-256w.jpg 256w, dog-512w.jpg 512w, dog-1028w.jpg 1028w"
src="dog-256w.jpg"
alt="Photo of a dog on a orange background">
<!-- Picture tag -->
<picture>
<source media="(max-width: 720px)" width="600" height="300" srcset="newyork-rectangle.jpg" />
<source media="(min-width: 721px)" width="600" height="600" srcset="newyork-square-1x.jpg, newyork-square-2x.jpg 2x, newyork-square-3x.jpg 3x" />
<img src="newyork-rectangle.jpg" width="600" height="300" alt="Photo of the Empire State Building">
</picture>