10 August, 2021

Better Nextjs Responsive Images using Sizes

The Sizes attribute

The Nextjs image component enables us to easily provide Image Optimisation for either locally stored media, or by using a loader, from the Dynamic Media services from Cloudinary or Imgix.

We covered some thoughts the defaults for the srscet candidate list in a previous post

The other important default to pay attention to is sizes. The sizes attribute is needed to describe to the browser how much of your layout's width they images take up under various circumstances (i.e at different viewport widths.

The default for sizes is effectively size='100vw' Which is fine, if your media does indeed span the whole of the viewport width under all circumstances. But if this is not the case, then the maths that the user agent uses to determine which srcset candidate to use, is probably incorrect - and hence you may well be loading images which are larger than neccesary, and therefore heavier.

For the image on the 'about' page i use:

    sizes="(max-width: 1140px) 100vw,1140px"

This indicates to the browser that for viewport widths less than 1140px, the image is indeed 100% of the width (100vw) - and this is used to calculate which image candidate should be requested, for example at 800px wide, the browser might request the srcset matching 828w - unless you have a 2 DPR screen, in which case it would request the 1920w candidate.

Beyond viewport widths 1140px wide, the way my layout is designed, the image doesn't actually get any larger, as it is in a column whose widths remains fixed after that point - in which case, for all viewport widths bigger than 1140px the User Agent will request the 1200w srcset candidate for 1DPR screens, or for 2DPR screen it will actually select the 3840w candidate - and this is a great example of why you might want to consider different deviceSizes from my previous post

Back to blog posts list