You are currently viewing HTML Media Elements

HTML Media Elements

 additioMedia elements in the evolving web development landscape have become essential tools for creating interactive and engaging user experiences. HTML media elements enable developers to easily incorporate various types of content, such as audio, video, and images, directly into websites. This enhances both the functionality and aesthetics of the pages.

Similarly, Media elements allow websites to be more dynamic, increasing user engagement and conveying information in ways that text alone cannot. 

By effectively understanding and using HTML media elements, developers can deliver highly interactive and accessible content that improves user experience, boosts SEO, and enhances overall site performance.

6 Types of HTML Media Elements

HTML Media Element Purpose Attributes Example Use Case
<audio> Embeds audio content on a webpage controls, autoplay, loop, muted, src

preload

<audio controls><source src="audio.mp3" type="audio/mpeg"></audio>
Embedding background music or podcasts
<video> Embeds video content on a webpage controls, autoplay, loop

muted

width

height, poster

src

<video controls><source src="video.mp4" type="video/mp4"></video>
Embedding video tutorials or product demos
<img> Embeds images on a webpage src

alt

width

height, loading

<img src="image.jpg" alt="Description of image" width="500" height="300">
Displaying product images or visual content
<picture> Responsive image handling with multiple sources srcset

sizes

media, type

<picture><source srcset="image-large.jpg" media="(min-width: 800px)"><img src="image.jpg"></picture>
Optimizing images for different screen sizes
<track> Adds text tracks (subtitles, captions) to videos src

kind

srclang, label, default

<video controls><track src="subtitles.vtt" kind="subtitles" srclang="en" label="English"></video>
Providing subtitles or captions in multiple languages
<embed> Embeds external resources, such as media or documents src

type

Width,

 height

<embed src="document.pdf" type="application/pdf" width="600" height="500">
Embedding PDFs, Flash (deprecated), and other media types
<object> Embeds external content data

type

width

height, usemap

form, <param>

<object data="document.pdf" type="application/pdf" width="600" height="500"><p>Fallback content</p></object>
Embedding interactive content, such as web applications or multimedia

 

1. Audio Element (<audio>)

The <audio> element in HTML embeds sound files on a webpage. It supports various audio formats, including MP3, OGG, and WAV. <audio> element is a versatile tool for adding podcasts, music tracks, sound effects, or audio content directly into your site without needing third-party plugins.

Example of Embedding Audio in HTML:

<audio controls>

  <source src="audio-file.mp3" type="audio/mpeg">

  <source src="audio-file.ogg" type="audio/ogg">

  Your browser does not support the audio element.

</audio>

In this example, the <audio> tag includes two different audio file formats (MP3 and OGG) for broader browser compatibility. The text between the tags is displayed if the browser doesn’t support the element.

Common Attributes of the <audio> Element:

  1. controls: Displays built-in playback controls like play, pause, and volume adjustment.
<audio controls>

  <source src="song.mp3" type="audio/mpeg">

</audio>
  1. autoplay: Starts playing the audio automatically when the webpage loads. This should be used carefully, as it may disrupt user experience.
<audio autoplay>

  <source src="background-music.mp3" type="audio/mpeg">

</audio>
  1. loop: Continuously plays the audio in a loop.
<audio controls loop>

  <source src="theme.mp3" type="audio/mpeg">

</audio>
  1. muted: Starts the audio in a muted state.
<audio controls muted>

  <source src="announcement.mp3" type="audio/mpeg">

</audio>
  1. preload: Defines whether the audio should be preloaded before the user plays it. Values can be:
  • auto (default): Preloads the audio when the page loads.
  • metadata: Preloads only metadata (duration, etc.).
  • none: No preloading.
<audio controls preload="metadata">   <source src="podcast.mp3" type="audio/mpeg"> </audio>

2. HTML Video Element (<video>)

The <video> element in HTML embeds video content into a web page without requiring third-party plugins like Flash. 

It supports multiple video formats, such as MP4, WebM, and Ogg, making it accessible across various browsers and devices. Similarly, it has built-in support for controls and customization options. 

<video controls width="600">   <source src="video-file.mp4" type="video/mp4">   <source src="video-file.webm" type="video/webm">   Your browser does not support the video tag. </video>

This example provides the video in MP4 and WebM formats to ensure compatibility across browsers. The text inside the <video> tag appears only if the browser doesn’t support HTML5 videos.

Common Attributes of the <video> Element:

  1. controls: Displays video controls (play, pause, volume, etc.) provided by the browser.
<audio controls>

  <source src="song.mp3" type="audio/mpeg">

</audio>
  1. autoplay: Starts playing the audio automatically when the webpage loads. This should be used carefully, as it may disrupt user experience.
<audio autoplay>

  <source src="background-music.mp3" type="audio/mpeg">

</audio>
  1. loop: Continuously plays the audio in a loop.
<audio controls loop>

  <source src="theme.mp3" type="audio/mpeg">

</audio>
  1. muted: Starts the audio in a muted state.
<audio controls muted>

  <source src="announcement.mp3" type="audio/mpeg">

</audio>
  1. poster: Specifies an image to display before the video starts playing. This is useful for showing a preview image or video thumbnail.
<video controls poster="poster-image.jpg">

  <source src="movie.mp4" type="video/mp4">

</video>
  1. preload: Determines whether or not the video should be preloaded before the user plays it. The attribute values are:
  • auto: Preloads the entire video.
  • metadata: Preloads only the video’s metadata (e.g., duration).
  • none: No preloading occurs; the video will load only when clicked.
<video controls preload="metadata">

  <source src="sample-video.mp4" type="video/mp4">

</video>

Advanced HTML Media Elements

  1. Subtitles and Captions with <track>: The <video> element can be combined with the <track> tag to provide subtitles or captions for improved accessibility and better user experience.
<video controls>

  <source src="lecture.mp4" type="video/mp4">

  <track src="subtitles_en.vtt" kind="subtitles" srclang="en" label="English">

  <track src="subtitles_fr.vtt" kind="subtitles" srclang="fr" label="French">

</video>

This example provides English and French subtitles for the video.

  1. Multiple Video Sources: Like the <audio> element, you can include multiple video sources in different formats to ensure browser compatibility.
<video controls>

  <source src="video-file.mp4" type="video/mp4">

  <source src="video-file.webm" type="video/webm">

  <source src="video-file.ogv" type="video/ogg">

</video>

Browser Support for Video Formats:

Different browsers support different video formats. Here’s a quick breakdown:

  • MP4 (H.264): Widely supported across most browsers, including Chrome, Safari, Internet Explorer, and Firefox.
  • WebM: Open format supported by Chrome, Firefox, and Opera.
  • Ogg: Supported by Firefox and Opera, though its usage is less common.

Fallback Content:

For older browsers not supporting the <video> element, you can provide fallback content like links to the video file for download.

3. Image Element (<img>)

The <img> element is used in HTML to embed images into a webpage. Unlike other media elements such as <audio> or <video>, the <img> element is self-closing, meaning it doesn’t have a closing tag.

 Images are essential for providing visual content that can complement text, enhance storytelling, or even serve as the primary content in some instances, such as in galleries or portfolios.

The primary purpose of the <img> tag is to display images on a webpage. Images play a critical role in web design, offering users visual representation, navigation aids, and enhanced aesthetics. They can be used for a variety of purposes, including:

  • Product photos in e-commerce websites.
  • Infographics to explain data or concepts visually.
  • Banners or advertisements for marketing.
  • Thumbnails for videos or articles.
  • Illustrations for blogs and social media content.

Example of <img> Usage:

Here’s an example of a basic image embedded using the <img> tag:

<img src="landscape.jpg" alt="Beautiful Mountain Landscape" width="600" height="400">

In this example:

  • src=”landscape.jpg” is the source attribute pointing to the image file’s location.
  • alt=”Beautiful Mountain Landscape” is the alternative text that describes the image for screen readers and search engines.
  • width=”600″ and height=”400″ define the image’s display size in pixels.

Key Attributes of the <img> Element:

  1. src (Source): This attribute is mandatory and specifies the path to the image file. The image file can be hosted locally or externally. 

It’s best practice to use the relative path if the image is in the same directory as your HTML file or the absolute path if it is hosted elsewhere.

<img src="images/pic.jpg" alt="Picture">

Local example: src=”images/photo.jpg”

External example: src=”https://example.com/photo.jpg”

  1. alt (Alternative Text): The alt attribute provides a text description of the image, which is displayed when the image cannot be loaded. 

More importantly, it is used by screen readers for accessibility, allowing visually impaired users to understand what the image represents. It is also essential for SEO, as search engines use the alt text to index images.

<img src="portrait.jpg" alt="Portrait of a smiling woman">
  1. width and height: These attributes define the image’s dimensions in pixels. Specifying these dimensions is vital to ensure the browser knows how much space to allocate for the image even before it fully loads. 

You can automatically set only one of these attributes to maintain the aspect ratio.

<img src="logo.png" alt="Company Logo" width="200">
  1. title: This attribute displays a tooltip when the user hovers over the image.
<img src="icon.png" alt="Information Icon" title="More Information">
  1. loading: This attribute is used for lazy loading, which defers the loading of off-screen images until the user scrolls to them. 

This improves performance, especially on pages with multiple images.

  • lazy: Delays the loading until necessary (i.e., when the user scrolls to the image).
  • eager: Forces the image to load immediately.
<img src="gallery-image.jpg" alt="Gallery Image" loading="lazy">
  1. srcset and sizes: These attributes allow for responsive images, serving different image versions based on screen size, resolution, or other factors.
<img srcset="image-400w.jpg 400w, image-800w.jpg 800w" sizes="(max-width: 600px) 400px, 800px" src="image-800w.jpg" alt="Responsive Image">
  • srcset: Specifies different image files for different screen resolutions.
  • sizes: Defines the width of the image based on screen size, helping to load the appropriate image.

4. Picture Element (<picture>)

The <picture> element in HTML is a more advanced tool for responsive image handling. It allows web developers to specify multiple image sources so that the browser can choose the most appropriate one. This is done based on the user’s device or screen size.

This HTML media element is beneficial for optimizing images for different screen resolutions and providing different versions of the same image depending on the device type (mobile, tablet, desktop).

Unlike the primary <img> tag, the <picture> element gives more control over image selection, allowing developers to serve different image formats, resolutions, or orientations depending on the user’s environment. 

This helps improve page load speed and provides a better user experience, especially on smaller or high-resolution devices.

Example with Different Image Sources for Various Screen Sizes:

<picture>

  <source media="(min-width: 1200px)" srcset="image-large.jpg">

  <source media="(min-width: 768px)" srcset="image-medium.jpg">

  <source media="(max-width: 767px)" srcset="image-small.jpg">

  <img src="image-default.jpg" alt="A beautiful landscape">

</picture>

Explanation:

  • <source> Elements: Each <source> tag defines a media query (media) and an image source (srcset). The browser evaluates the media queries and selects the appropriate image based on the user’s device and screen size.
  • media=”(min-width: 1200px)” srcset=”image-large.jpg”: This image is displayed for screens that are 1200 pixels or wider (e.g., desktops).
  • media=”(min-width: 768px)” srcset=”image-medium.jpg”: This image is displayed for screens that are between 768 and 1199 pixels wide (e.g., tablets).
  • media=”(max-width: 767px)” srcset=”image-small.jpg”: This image is shown on devices with screens narrower than 768 pixels (e.g., smartphones).

Fallback <img> Tag: If the browser doesn’t support the <picture> element or none of the specified media queries apply, the default <img> tag will be used. This ensures the image still displays, although it may not be as optimized for the screen size.

Another Example with Different Formats:

<picture>

  <source type="image/webp" srcset="image.webp">

  <source type="image/jpeg" srcset="image.jpg">

  <img src="image.jpg" alt="A scenic view of mountains">

</picture>

In this example:

  • type=”image/webp”: This specifies that the browser should load the WebP image format if supported (WebP is highly compressed, allowing faster loading times).
  • type=”image/jpeg”: If WebP is not supported, the browser will fall back to the JPEG format.

5. Track Element (<track>)

The <track> element in HTML is used to specify text tracks (such as subtitles, captions, or metadata) for <video> and <audio> elements. 

It enhances accessibility and user experience by providing additional text-based information that can be displayed alongside the media. This is especially useful for users who are hearing impaired or watching content in a different language.

The <track> element must be used inside either a <video> or <audio> element, and it does not display by itself. Instead, it pairs with the media to offer a synchronized text layer, such as subtitles or descriptions.

Types of Tracks Supported by <track>:

  • Subtitles: Translating the spoken words in a video into different languages.
  • Captions: Provide a text alternative for both the spoken dialogue and relevant sounds (e.g., “door creaks,” “birds chirping”), useful for hearing-impaired users.
  • Descriptions: Describe visual elements for visually impaired users.
  • Chapters: Break the media into sections, making it easier for users to navigate between parts.
  • Metadata: Can contain extra information about the media that’s not intended to be displayed but used programmatically.

Attributes of the <track> Element:

  • src: Specifies the URL of the track file (e.g., .vtt file format).
  • kind: Defines the track type, such as subtitles, captions, descriptions, chapters, or metadata.
  • srclang: Specifies the language of the track (e.g., “en” for English, “fr” for French).
  • Label: Provides a label that users will see when selecting the track (e.g., “English Subtitles”).
  • Default: Marks the track as the default track if multiple tracks exist.

Example Usage:

Here’s an example of how the <track> element is used within a <video> element to provide subtitles in two different languages (English and French):

<video controls>

  <source src="movie.mp4" type="video/mp4">

  <track src="subtitles_en.vtt" kind="subtitles" srclang="en" label="English" default>

  <track src="subtitles_fr.vtt" kind="subtitles" srclang="fr" label="French">

</video>

Explanation:

The <video> tag contains the video file (movie.mp4), and within it, two <track> elements are provided for subtitles.

src=”subtitles_en.vtt”: This points to the English subtitle file.

kind=”subtitles”: Specifies that this track provides subtitles.

srclang=”en”: Indicates that the subtitles are in English.

label=”English”: The label is displayed for users when they choose subtitles.

  • default: This attribute makes the English subtitles the default selection.

The second <track> element specifies subtitles in French, allowing users to switch between languages.

6. Embedded Content (<embed> and <object>)

The <embed> and <object> elements in HTML directly incorporate external resources, such as multimedia content or interactive elements, into a webpage. 

They can handle different files, such as PDFs, Flash content, audio files, and other media. However, each element serves a different purpose and has distinct use cases.

Difference Between <embed> and <object>:

<embed>:

The <embed> element is a self-contained tag used to embed external resources directly into a webpage. It is often used to embed multimedia files like videos, audio, and documents without much configuration.

It is simpler but less flexible than <object>, as it doesn’t allow for fallback content or alternative file types if the embedded file doesn’t load properly.

<object>:

The <object> element is more versatile and allows for embedding external files, such as images, audio, videos, PDFs, and other interactive content.

It supports fallback content, meaning alternative content or media can be displayed if the browser cannot load the primary resource.

In addition, it also allows for better customization, such as embedding Flash files (now deprecated) or more complex web applications. It can also handle interactive content like Java applets (though these technologies are now less common).

Example 1:

<embed src="document.pdf" type="application/pdf" width="600" height="500">

The PDF file is embedded in this example, and the browser’s PDF viewer will handle its display.

Examples 2: Using <object> (with fallback content):

<object data=”document.pdf” type=”application/pdf” width=”600″ height=”500″>

  <p>Your browser does not support PDFs. Please download the PDF to view it: 

  <a href=”document.pdf”>Download PDF</a>.</p>

</object>

If the browser cannot display the PDF, it will show a fallback message and a download link.

Embedding Audio or Video Files in HTML

Both tags can embed audio or video files. However, modern websites typically use the <audio> or <video> elements. In other words, both  can still serve multimedia files when needed.

Example 1:  Using <embed>:

<embed src="audiofile.mp3" type="audio/mpeg" width="300" height="32" controls>

Example 2: Using <object> (with fallback):

<embed src="audiofile.mp3" type="audio/mpeg" width="300" height="32" controls>

When to Use <embed> vs. <object>:

  • Use <embed> when:
    • You must quickly embed media (like a video or PDF) without complex fallback options.
    • You prefer simplicity and do not need to handle unsupported scenarios.
  • Use <object> when:
    • You want to provide fallback content if the user’s browser doesn’t support the embedded resource.
    • You need more versatility in embedding, such as supporting different media types or adding interaction.
    • You are embedding more complex web applications or media that require additional parameters.

The choice between <embed> and <object> depends on the complexity of your media embedding needs and how much control you want over fallback content and customization. For most modern websites, <embed> is used for simple media, while <object> provides more flexibility and control over the embedded content.

<embed src="audiofile.mp3" type="audio/mpeg" width="300" height="32" controls>

Leave a Reply