The HTML <source> tag
The HTML <source> element provides one of several candidate media resources for a <picture>, <audio> or <video>. The browser picks the first suitable one based on type, media or srcset.
Overview
The <source> element is a void element that offers an alternative resource to its parent media element. Its meaning shifts depending on where it lives, which is the key thing to understand.
Inside an <audio> or <video>, each <source> offers a different file format, and the browser plays the first one it can handle — so you list, say, a WebM and an MP4 and let the browser choose. Inside a <picture>, it offers different images: with the media attribute for art direction (different crops at different screen sizes) or with srcset for resolution switching and modern formats like AVIF and WebP.
Order matters in both cases — the browser uses the first matching <source> — and there should always be a fallback after the sources: an <img> inside a picture, or fallback text inside audio/video.
Syntax
<source src="clip.webm" type="video/webm">
Attributes
The <source> element supports the following attributes, in addition to the global attributes available to every HTML element.
| Attribute | Value | Description |
|---|---|---|
height |
A non-negative integer (pixels). | Sets the height of the element in pixels. |
media |
A media query, e.g. (min-width: 600px) or print. |
Applies the resource to matching media only. |
sizes |
A comma-separated list of media-condition / length pairs, e.g. (max-width:600px) 480px, 1080px. |
Defines image display size for srcset selection. |
src |
A URL pointing to the resource. | Specifies the URL of an embedded resource. |
srcset |
A comma-separated list of "URL descriptor" pairs, e.g. small.jpg 480w, large.jpg 1080w or 1x/2x. |
Lists responsive image candidates. |
type |
A MIME type such as text/css or image/webp — or module on a <script>. |
Specifies the MIME type of a resource. |
width |
A non-negative integer (pixels). | Sets the width of the element in pixels. |
Example
<picture>
<source srcset="logo.avif" type="image/avif">
<img src="https://codeshack.io/web/img/icon.png" alt="Logo" width="64" height="64">
</picture>
Best practices
- List sources in priority order — the browser uses the first match.
- In audio/video, use the
typeattribute so the browser can skip formats it cannot play without downloading them. - In <picture>, use
mediafor art direction andsrcsetfor resolution and modern formats. - Always include a fallback after the sources — an <img> or fallback text.
Frequently asked questions
What is the source element for?
How do I provide multiple video formats?
<source> elements with different src and type values inside the <video>; the browser plays the first it supports.