@lightpohl

Dev Notes #1 — Picture Element Basics

June 4th, 2021

Dev notes are shorter posts in a draft-like quality and typically include a code example.

If an <img> source needs to be changed based on media breakpoints, we can use a <picture> element to do just that and also support higher pixel density screens.

For this example, let's say we're building a photo grid component that needs to work at three breakpoints: mobile, tablet, and desktop.

We need a higher resolution image for mobile and tablet views than we do for desktop. We'll define two <source> elements inside of each <picture> with media properties — one for tablet and one for desktop. The default <img> inside of the <picture> will take care of our mobile size.

<picture>
	<source
	  media="(min-width: 801px)"
	  srcset="image-200.jpeg, image-300.jpeg 1.5x, image-400.jpeg 2.0x"
	>
	<source
	  media="(min-width: 501px)"
	  srcset="image-300.jpeg, image-450.jpeg 1.5x, image-600.jpeg 2.0x"
	>
	<img
	  loading="lazy"
	  src="image-500.jpeg"
	  srcset="image-500.jpeg, image-750.jpeg 1.5x, image-1000.jpeg 2.0x"
	/>
</picture>