HTML <source> Element

Publish in HTML Tutorial el 25/05/2025 16:19

The <source> element is used to specify multiple media resources for media elements like <audio>, <video>, and <picture>. It allows you to provide alternative media formats for better browser compatibility and responsive design.


Key attributes of <source>:

  • src: Specifies the URL of the media file
  • type: Defines the MIME type of the media resource
  • media: Specifies media queries for responsive images
  • srcset: Used with <picture> for responsive images
  • sizes: Defines image sizes for different layouts


Basic Syntax


Example 1: Multiple Video Formats

This example shows how to provide fallback video formats using <source>. The browser will try each source in order until it finds a format it supports.

Play Code


Example 2: Responsive Images with <picture>

The <source> element can be used with <picture> to serve different images based on viewport size or device capabilities.

Play Code


Example 3: Audio with Fallback Formats

Similar to video, you can provide multiple audio formats for better browser compatibility.

Play Code


Example 4: Dynamic Source Change with JavaScript

This example demonstrates how to change the video source dynamically using JavaScript.

Play Code


Example 5: Checking Supported Formats with JavaScript

This example shows how to detect which media formats are supported by the browser.

Play Code


Tips and Tricks

  • Always specify the type attribute to help browsers determine if they can play the media without downloading it first
  • Order sources from most preferred to least preferred format
  • For video, place higher quality formats first (like WebM before MP4)
  • Use media queries with <picture> to optimize image delivery for different screen sizes
  • Consider using the srcset attribute for resolution switching with responsive images

También te puede interesar

HTML <style> Element
HTML <style> Element

The <style> HTML element contains style information for a document, or part of a document. ...

HTML <strong> Element
HTML <strong> Element

The <strong> element is used to indicate that its content has strong importance, seriousnes...

HTML <span> Element
HTML <span> Element

The <span> element is an inline container used to mark up a part of a text or document. Unl...

HTML <small> Element
HTML <small> Element

The <small> element is used to represent side-comments and small print, typically for discl...

HTML <section> Element
HTML <section> Element

HTML <section> Element: The Complete Guide The <section> element is a semantic HTML ...

HTML <script> Element
HTML <script> Element

The <script> HTML element is used to embed or reference executable code, typically JavaScri...