Using responsive images helps your website load faster, improves your SEO, and gives you more design control of your site when visited in different device sizes. Let's take a look at how Prismic makes it easy to set up responsive images using the picture element.

This example will show you how to set up an image for three different screen sizes: desktop, tablet, and mobile.

Set up the Image field

You can set up multiple image resolutions in Prismic by adding different sizes.

In the Custom type builder, we go to the configuration of the Image field and define the sizes for the three views, in this example, it has an API ID of "illustration":

Upload and edit the image and add metadata to it

In the writing room, click on the Image field to select an existing image from the Media Library or upload a new one. Then click the "Crop & Resize" button to reframe, zoom, and/or crop the image.

Retrieve the Image from the API and template it

All that is left to do is integrate these images into your design. In this example, the Custom type has the type of "Page".

Before Reading This page assumes that you have retrieved your content and stored it in a variable named document.

ReactJS example code snippet:

import React from "react"

const ResponsiveImages = ({ data }) => {

const document = data.results;
const desktop = document.illustration
const tablet = document.illustration.tablet
const mobile = document.illustration.mobile

return (
<picture>
<source
srcSet={mobile.url}
alt={mobile.alt}
media="(max-width: 400px)"
/>
<source
srcSet={tablet.url}
alt={tablet.alt}
media="(max-width: 900px)"
/>
<img
src={desktop.url}
alt={desktop.alt}
/>
</picture>
)
}
export default ResponsiveImages

PugJS example code snippet:

- const document = data.results;
- const desktop = document.getImage("document.illustration")
- const tablet = document.getImageView("document.illustration", "tablet")
- const mobile = document.getImageView("document.illustration", "mobile")

picture
// mobile
source(media='(max-width: 400px)', srcset=mobile.url, alt=mobile.alt)
// tablet
source(media='(max-width: 900px)', srcset=tablet.url, alt=tablet.alt)
// desktop
img(srcset=desktop.url, alt=desktop.alt)

The picture element. is quickly becoming the standard for responsive images and is supported by almost all the major browsers. For the few browsers that do not yet support it, we suggest using a responsive image polyfill like Picturefill to fill that gap.

Well done!

You’ve successfully set up your image field to handle responsive images. Use this technique for all your images to make sure that your website is loading the right image for the right screens.

Did this answer your question?