<source>

The HTML <source> element defines various media sources for <audio> or <video> elements, enabling the browser to choose the best format or quality according to user preferences and device capabilities.

source tag

The <source> tag in HTML5 is used to define multiple media resources, such as audio, video, or images, ensuring better compatibility across different browsers. By including multiple <source> elements, the browser can select the best available option for smooth playback.

Syntax

index.html
<source src="URL" type="MIME-type">

Example for <video>

index.html
<video controls>
  <source src="/cs/html/videos/video2.mp4" type="video/mp4">
</video>

Example for <audio>

index.html
<audio controls>
  <source src="audio.mp3" type="audio/mpeg">
</audio>

Attributes

The <source> element supports the following attributes:

  • type: Specifies the MIME type of the media, which may include a codecs parameter.
  • src: Defines the URL of the media resource. This is required for <audio> and <video> but is not used within <picture>.
  • srcset: Provides a list of image sources along with descriptors. It is used within <picture> but does not apply to <audio> or <video>.

sizes

Defines a list of source sizes for rendering the image at different widths. This attribute is only used inside a <picture> and does not apply to <audio> or <video>.

media

Sets a media query to determine when the source file should be used.

height

Specifies the image's intrinsic height in pixels. Only applicable within a <picture> and not used for <audio> or <video>.

width

Specifies the image's intrinsic width in pixels. Only applicable within a <picture> and not used for <audio> or <video>.

Conclusion

The <source> tag in HTML5 is used to define multiple media resources, allowing browsers to select the best option for smooth playback. It is commonly used with <video> and <audio> tags, specifying the src and type attributes for media files. It also supports the media attribute for conditional resource selection based on device characteristics.