HTML · Course navigation

HTML Responsive Images and Media

Offer different image files for different screens and embed video with a fallback.

On this page

The concept

One image file rarely suits every screen. The picture element lets the browser choose a source by a media query. The srcset and sizes attributes describe several widths of the same image, and the browser picks the smallest file that is sharp enough for the layout and screen. Always give images width and height so the page does not jump while they load, and use loading="lazy" for images below the fold. The video element needs controls, and text inside it is shown by browsers that cannot play it.

Code example

HTML
<picture>
  <source media="(min-width: 800px)" srcset="wide.jpg">
  <img src="narrow.jpg" alt="A mountain lake at sunrise" width="800" height="450" loading="lazy">
</picture>
<img srcset="small.jpg 480w, large.jpg 960w"
     sizes="(min-width: 600px) 50vw, 100vw"
     src="small.jpg" alt="Product photo" width="480" height="320">
<video controls width="320">
  <source src="clip.mp4" type="video/mp4">
  Your browser does not support video.
</video>

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1<picture>
2 <source media="(min-width: 800px)" srcset="wide.jpg">
3 <img src="narrow.jpg" alt="A mountain lake at sunrise" width="800" height="450" loading="lazy">
4</picture>
5<img srcset="small.jpg 480w, large.jpg 960w"
6 sizes="(min-width: 600px) 50vw, 100vw"
7 src="small.jpg" alt="Product photo" width="480" height="320">
8<video controls width="320">
9 <source src="clip.mp4" type="video/mp4">
10 Your browser does not support video.
11</video>

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
picture wraps several possible sources for one image.—
—
On screens at least 800px wide, the browser uses wide.jpg.—
—
The img is the fallback and carries the alt text. width and height reserve space, and lazy loading delays the download until needed.—
—
srcset lists the files and their real widths in pixels.—
—
sizes tells the browser how wide the image will be shown, so it can choose a file before the layout is calculated.—
—
controls shows play, pause, and volume. Browsers render the video; there is no console output.—
—

Behind the scenes

How HTML processes this code

The browser parses HTML into a document tree and renders its elements. HTML does not execute as a sequence of program statements.