Use Responsive Image to reserve space for an image and prevent page content from jumping around once the image loads.
Use Responsive Image...
- When you know the aspect ratio of an image.
- When you need the image to load immediately.
Don’t use Responsive Image…
- When you don’t know the image’s aspect ratio ahead of time. Use Fluid Image instead.
- When you can defer the loading of the image. Use Progressive Image instead.
BasicResponsiveImage
BasicResponsiveImage
is a React convenience component that covers most use cases. It takes an aspectRatio
prop with the image’s aspect ratio, plus any props like alt
and src
that can go onto an <img>
tag.
The aspect ratio should be the image's height divided by its width:
e.g. 1) If your image is 160px wide and 90px tall, your aspect ratio is 90 / 160 = 0.5625
e.g. 2) If your image is a square, your aspect ratio is 1
Multiple source images
Use the srcset
prop to set the corresponding srcset
attribute on the underlying <img>
tag, so that you can provide both hi-res and lo-res versions of an image. The browser will only download the relevant version for the user’s screen size, resulting in better page performance. Refer to srcset at MDN.
Using a <picture> tag
Use React’s as
prop to have the component produce a <picture>
tag instead. Refer to picture at MDN.
ResponsiveImageContainer
In the Vanilla API, or when you need more control over the code than BasicResponsiveImage
provides, use the underlying components that BasicResponsiveImage
is made of: a ResponsiveImageContainer
around a ResponsiveImage
.
In the React API, use the aspectRatio
prop on the ResponsiveImageContainer
, which is the outer wrapper around the image. All the other props, including srcset
, go onto the child ResponsiveImage
, which produces the <img>
tag.
In the vanilla API, you must set an inline padding-bottom
on the swan-responsive-image-wrapper
element, whose value is the image's aspect ratio, expressed as a percentage. So an image with an aspect ratio of 0.5625 needs an inline padding-bottom: 56.25%
.
Alt text
All Responsive Images need an alt attribute of some kind. Refer to “Alt text” guidelines.