Tag Picture in Html

The picture element is a markup pattern that allows developers to declare multiple sources for an image.

This markup is a container used to specify multiple <source> elements for a specific <img> contained in it.

1
2
3
4
5
6
7
<picture>
<source media="(min-width: 40em)"
srcset="big.jpg 1x, big-hd.jgp 2x">
<source
srcset="small.jpg 1x, small-hd.jpg 2x">
<img src="fallback.jpg">
</picture>

Use the media attribute

The media attribute lets you specify a media query that the user agent will evaluates to select a <source> element. If the media query evaluates to false, the <source> element is skipped.

1
2
3
4
<picture>
<source srcset="logo-wide.jpg" media="(min-width: 600px)">
<img src="logo-narrow.jpg">
</picture>

The srcset and sizes attributes extend the img and source elements to provide a list of available image sources and their sizes. Browsers can then use this information to pick the best image source.

1
2
3
4
5
6
7
<img srcset="elva-fairy-320w.jpg 320w,
elva-fairy-480w.jpg 480w,
elva-fairy-800w.jpg 800w"
sizes="(max-width: 320px) 280px,
(max-width: 480px) 440px,
800px"
src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy">

srcset defines the set of images we will allow the browser to choose between, and what size each image is.

Before each comma, we write:

  • An Image filename (elva-fair-320w.jpg)

  • A space

  • The image’s inherit width in pixels(480w) – note that this issue the w unit, not px as you might expect.

sizes defines a set of media conditions(e.g. screen widths) and indicates what image size would be best to choose, when certain media conditions are true.

Before each comma, we write:

  • A media condition(max-width: 480px) – when the viewport width is 480 px or less

  • A space

  • The width of the slot the image will fill when the media condition is true(440px)

Resolution switching

1
2
3
4
5
6
7
<img
srcset="elva-fairy-320w,jpg,
elva-fairy-480w.jpg 1.5x,
elva-fairy-640w.jpg 2x"
src="elva-fairy-640w.jpg"
alt="elva-fairy"
>
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×