The <source> HTML element is used to specify multiple media resources for elements like <audio>, <video>, and <picture>. It allows developers to provide different versions of a media file or image to accommodate various formats and conditions, such as browser compatibility or screen size. The browser will choose the first <source> element that it supports.
Usage and Characteristics
The <source> element is a void element, meaning it does not have a closing tag. It is typically used within <audio>, <video>, or <picture> elements to provide alternative media sources. Here are examples of how the <source> tag can be used in different contexts:
Video Element:
<video controls>
<source src="video.mp4" type="video/mp4">
<source src="video.webm" type="video/webm">
Your browser does not support the video tag.
</video>Audio Element:
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
<source src="audio.ogg" type="audio/ogg">
Your browser does not support the audio tag.
</audio>Picture Element:
<picture>
<source srcset="image-large.jpg" media="(min-width: 800px)">
<source srcset="image-medium.jpg" media="(min-width: 500px)">
<img src="image-small.jpg" alt="A description of the image">
</picture>Valid Attributes for <source>
| Attribute | Description |
|---|---|
| src | Specifies the URL of the media file. Used in |
| type | Specifies the MIME type of the media resource. Helps the browser determine how to process the file. |
| srcset | Specifies a list of image sources for different device resolutions or conditions. Used in |
| media | Defines the media condition (e.g., screen width) that must be met for the source to be used. Used in |
| sizes | Specifies the image sizes for different viewport widths. Used in |
Benefits and Considerations
Flexibility: The
<source>element provides flexibility by allowing developers to specify multiple formats of a media resource, ensuring compatibility across different browsers and devices.Responsive Design: In the context of the
<picture>element,<source>helps implement responsive images by delivering the most appropriate image based on screen size and resolution.Fallback Support: By providing multiple
<source>elements, developers can ensure that a suitable media file is available for a wide range of browsers, with fallback content available if none of the sources are supported.
In summary, the <source> element is a powerful tool for providing multiple media resources for <audio>, <video>, and <picture> elements. It enhances compatibility, responsiveness, and user experience by allowing browsers to select the most suitable media file based on format support and device conditions.
