Skip to main content

HTML <source> Tag

The HTML <source> element is used to specify media resources for the <picture>, <audio>, and <video> elements. It allows web developers to specify multiple sources for a media element, allowing the browser to choose the most suitable source based on the user's device and network conditions.

This element is often used to provide the same media content in different file formats to ensure compatibility with a wide range of browsers, as different browsers may support different image and media file formats.

Here's an example of how to use the <source> element with the <picture> element:

<picture>
    <source srcset="image-large.jpg" media="(min-width: 800px)">
    <source srcset="image-medium.jpg" media="(min-width: 400px)">
    <img src="image-small.jpg" alt="A beautiful landscape">
</picture>

The above code will display a different image based on the width of the user's device. If the device has a width of 800px or more, the image-large.jpg image will be displayed. If the device has a width between 400px and 800px, the image-medium.jpg image will be displayed. If the device has a width of less than 400px, the image-small.jpg image will be displayed.

You can also use the <source> element with the <audio> and <video> elements to specify multiple sources for audio and video files. For example:

<audio controls>
    <source src="song.mp3" type="audio/mpeg">
    <source src="song.ogg" type="audio/ogg">
    Your browser does not support the audio element.
</audio>

The above code will allow the user to play an audio file in their browser. If the browser supports the MP3 format, the song.mp3 file will be played. If the browser doesn't support the MP3 format but does support the Ogg format, the song.ogg file will be played. If the browser doesn't support either format, the text "Your browser does not support the audio element." will be displayed.