Categories
HTML Web development

HTML source Tag


The HTML <source> tag defines multiple media resources for media elements, such as <audio>, <picture>, and <video>.

HTML source Tag

The HTML <source> element specifies alternative video/audio/image files which the browser can choose from, based on browser support (the browser will choose the first <support> it supports).

Example1:

The audio player with two source files (the browser will choose the first <source> it supports):

<!DOCTYPE html>
<html>
<body>

<audio controls>
  <source src="https://lenadesign.org/wp-content/uploads/2021/07/Wooden-Train-Whistle.mp3" type="audio/mpeg">
  <source src="https://lenadesign.org/wp-content/uploads/2021/07/Wooden-Train-Whistle.ogg" type="audio/ogg">
</audio>

</body>
</html>

Output:

Example2:

Use the HTML source element within <picture> element to specify different images based on the viewport width:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>

<picture>
  <source media="(min-width:650px)" srcset="https://lenadesign.org/wp-content/uploads/2022/01/css-diamond.gif">
  <source media="(min-width:465px)" srcset="https://lenadesign.org/wp-content/uploads/2021/12/cookie.png">
  <img src="https://lenadesign.org/wp-content/uploads/2021/06/ghost-example.jpg" alt="ghost" style="width:auto;">
</picture>

</body>
</html>

Output:

Resize the browser window to load different images:

ghost

Example3:

Use the HTML source element within <video> element to play the video:

<!DOCTYPE html> 
<html> 
<body> 

<video width="640" controls>
  <source src="https://videos.files.wordpress.com/lFj3lsG4/valentines-day-movie_dvd.mp4" type="video/mp4">
<source src="https://videos.files.wordpress.com/lFj3lsG4/valentines-day-movie_dvd.ogg" type="video/ogg">
</video>

</body> 
</html>

Output:

Attributes:

media (media_query) – accepts any valid media query specified in a CSS.

sizes – defines image sizes for different page layouts.

src (URL) – defines the URL of the media file (required when <source> is used in <audio> and <video>).

srcset (URL) – defines the URL of the media file (required when <source> is used in <picture>).

type (MIME-type) – defines the MIME-type of the resource.

Enjoy coding!

Read also:

HTML iframe tag

HTML link tag

HTML address tag