<picture>

Zoe Connolly
2 min readFeb 10, 2019

Working with the picture element in HTML.

The picture element is great for responsive images on the web. It allows you to change your image based on the width of your browser. This is beneficial to your user by having the option to load a smaller file size image when needed. This results in both faster load time and less data usage. As well as the ability to optimize your images based on browser size, this element can be used for art direction and create a better user experience.

How do you use the picture element?

Begin by having your images optimized and ready to go in your assets folder (you can have as many image options as you like).

Now let’s write some code! In your HTML start off with the picture element.

<picture>

</picture>

First, add your default image that your browser will fall back on if the picture element is not supported.

Between the opening and closing, tags add your img tag as you normally would.

It will look something like this:

<picture>

<img src=”assets/image.jpg” alt=”default image”>

</picture>

Now let’s put in the options for different screen sizes.

The options will be placed above the default image in the HTML. Use the self-closing tag ‘source’ in which there will be two different tags. The first will be ‘media’ in charge of applying the right image based on the screen size you choose, usually, the default is but not limited to: desktop 1024px, tablet 768px, 320px mobile. The second is ‘srcset’ where you put the path to the preferred image for the screen size.

It should not look something like this:

<picture>

<source media=”(min-width: 1024px)” srcset=”assets/imageOne.jpg”>

<source media=”(min-width: 768px)” srcset=”assets/imageTwo.jpg”>

<source media=”(min-width: 320px)” srcset=”assets/imageThree.jpg”>

<img src=”assets/image.jpg” alt=”default image”>

</picture>

Cool. Right, now how do you style this ?

Head into the CSS and target the default image inside your picture element and style that. The other images will inherit the styles applied to their sibling.

img{

display:block;

width: 100%;

}

The picture element is compatible with almost all browsers other than our friend internet explorer in which case it will default to the backup image we applied under our screen options.

There you go hope this was helpful and you give it a try in your next project

--

--

Zoe Connolly

Front end web developer and graphic designer based in Calgary, Alberta.