Popular Searches
Popular Course Categories
Popular Courses

Media

31 mins HTML5 & Semantic Markup

Media in React JS

Course: React JS Training

Topic: Media

Course Link: React JS Training

Demo Link: Register for a Course Demo


1. Media on the Web: Introduction and Why It Matters

Open any popular website and you will notice one thing quickly: the page is rarely just text. News portals lead with photographs, product pages show video demonstrations, music apps stream audio, and blogs embed maps and players from other services. All of this content is called media, and HTML5 gives you dedicated tags to place it on a page cleanly and reliably.

Before HTML5, playing a video or a song inside a browser usually required a third-party plugin such as Flash. HTML5 changed this by introducing native elements like <video> and <audio>. The browser itself now knows how to download, decode and play media files, which makes pages faster, safer and usable on phones where plugins never worked well.

For a future React developer this sub-module matters more than it first appears. React components ultimately render HTML, and a media gallery, a video lesson player or a product image carousel all sit on top of the plain HTML media tags you learn here. A weak foundation produces slow, inaccessible components; a solid one means you know exactly which attributes to reach for.

  • Performance: images and video are usually the heaviest files on a page, so correct media markup directly affects loading speed.
  • Accessibility: attributes like alt and elements like <track> make media usable for people who cannot see or hear it.
  • Search visibility: search engines read your media markup, including alt text and titles, to understand what a page offers.

2. What Are Media Elements? A Simple Definition

In plain words, a media element is an HTML tag that tells the browser: "fetch this file, which is not text, and show it or play it here." The file might be a photograph, a video clip, a podcast episode or even a whole web page from another site.

Media elements fall into two families, and the difference explains their structure:

  • Self-closing, replaced elements. Tags like <img> hold no content of their own. The browser takes the file named in the src attribute and replaces the empty tag with the actual picture. Nothing is written between the tags, so no closing tag is used.
  • Container elements. Tags like <video>, <audio> and <picture> have an opening and a closing tag. The space between them is not shown to the user; it holds fallback text for browsers that cannot play the file, plus child tags such as <source> or <track>.

Think of it this way: <img> is like an empty picture frame that the browser fills in, while <video> is like a small stage where you can place several props (different files, captions) along with instructions for the player.


3. Key Terms in HTML5 Media

These words appear throughout this sub-module and in every documentation page, so learn them now:

  • src — the source attribute; it holds the address (URL) of the media file.
  • Source element — the <source> tag, placed inside <video>, <audio> or <picture> to offer one or more files for the browser to choose from.
  • MIME type — the formal label of a file format, such as video/mp4 or image/webp, written in the type attribute so the browser can skip formats it cannot play.
  • Codec — the compression method inside a media file, for example H.264 inside an MP4 file. Two files can share a container format yet use different codecs.
  • Fallback — content shown when the preferred file or feature is unavailable, such as the text between <video> tags or a JPEG offered when WebP is not supported.
  • Poster frame — the image shown in a video player before the user presses play, set with the poster attribute.
  • Text track — timed text for media, such as subtitles or captions, supplied by the <track> element.
  • Lazy loading — telling the browser to download an image or frame only when the user scrolls near it, using loading="lazy".
  • Art direction — serving a differently cropped or shaped image depending on screen size, done with <picture>.
  • Embedding — placing content from another web page or service inside your page, usually with <iframe>.

4. The Media Element Family at a Glance

HTML5 offers several media-related tags. Each has a specific job, and choosing the right one is the first skill of this sub-module:

ElementWhat it doesTypical use
<img>Displays a single image filePhotos, logos, icons, illustrations
<picture>Container that lets the browser pick the best image fileFormat switching (WebP with fallback) or different crops per screen size
<audio>Plays a sound file, optionally with built-in controlsPodcasts, music clips, voice notes
<video>Plays a video file, optionally with built-in controlsTutorials, product demos, background clips
<source>Offers a file and its type inside audio, video or pictureMultiple formats so every browser finds one it can play
<track>Adds timed text such as captions to audio or videoSubtitles, captions, chapter navigation
<iframe>Embeds another HTML page inside the current pageMaps, video platforms, widgets from other sites
<embed> and <object>General-purpose embedding of external content such as PDFsSituations where no dedicated element fits

A useful habit: reach for <img>, <video> and <audio> first, because they are simple and well supported. Use <picture> when you need format or crop switching, and <iframe> only when the content genuinely lives on another page.


5. Syntax and Structure of Media Tags

Every media tag follows one of two shapes. The self-closing shape, used by <img> and <source>:

<img src="photo.jpg" alt="A student learning HTML at a desk">

The container shape, used by <video>, <audio> and <picture>:

<video src="lesson.mp4" controls width="640" height="360" poster="lesson-cover.jpg">
  Your browser does not support embedded video.
</video>

Notice three parts: the tag name, the attributes written inside the opening tag as name="value" pairs, and (for container tags) fallback text between the opening and closing tags. The fallback text appears only if the browser cannot handle the element at all, which is rare today but costs nothing to include.

The attributes you will use most often on <video> and <audio> are summarised below:

AttributeWhat it doesExample
srcAddress of the media filesrc="song.mp3"
controlsShows the browser's play/pause, volume and seek bar<audio controls>
autoplayTries to start playback as soon as the file loadsautoplay
mutedStarts the media with sound turned offmuted
loopRestarts playback from the beginning when it endsloop
preloadHints how much to download in advance: none, metadata or autopreload="metadata"
posterImage shown before the video plays (video only)poster="cover.jpg"
width / heightReserve space for the player on the pagewidth="640"

Boolean attributes such as controls, muted and loop work by their mere presence; you do not write controls="true". Writing just the word is the modern, correct style.


6. How the Browser Handles a Media Tag, Step by Step

Understanding the browser's decisions helps you predict why a page behaves the way it does. When the parser meets a media element, this sequence happens:

  1. Read the tag and its attributes. The browser notes the src, the size, and any behaviour flags such as controls or autoplay.
  2. Collect candidate files. If the element contains <source> children, the browser lists them in order. In <picture>, it also checks each source's media attribute against the current screen.
  3. Pick the first file it can play. Using the type attribute, the browser skips unsupported formats without downloading them. This is why listing WebM before MP4 works: browsers that play WebM take it, the rest fall through to MP4.
  4. Download according to preload. With preload="none" nothing is fetched until the user presses play; metadata fetches duration and dimensions only; auto lets the browser decide, usually the whole file.
  5. Decode and display. The browser decodes the file and renders it in the reserved box, or starts playing if autoplay was set and allowed.
  6. Show fallback if everything fails. If no file can be played, the text between the container tags is displayed instead.

One practical consequence: browsers block autoplay for media with sound. If you genuinely need automatic playback — for example, a muted background clip — combine autoplay with muted, and add playsinline on video so phones do not force full screen:

<video src="bg-loop.mp4" autoplay muted loop playsinline></video>

7. Worked Example: Adding an Image with <img>

The simplest media example is an image. Start minimal, then improve it:

<img src="team-photo.jpg">

This renders the picture, but it fails on three counts: there is no text alternative, the browser does not know the dimensions, and the file downloads even if it sits far below the visible screen. The improved version fixes all three:

<img src="team-photo.jpg"
     alt="The training team standing in front of a whiteboard"
     width="800" height="500"
     loading="lazy">
  • alt describes the image for screen readers and for anyone whose connection blocks the file. If an image is purely decorative, an empty alt="" is the correct choice, because it tells assistive technology to skip it.
  • width and height let the browser reserve the right box before the image arrives, preventing the page from jumping as content loads.
  • loading="lazy" postpones the download until the user scrolls close to the image, which is ideal for long pages and galleries.

You can also give the browser size hints with srcset and sizes, letting it download a smaller file on phones and a larger one on desktops:

<img src="banner-800.jpg"
     srcset="banner-400.jpg 400w, banner-800.jpg 800w, banner-1600.jpg 1600w"
     sizes="(max-width: 600px) 400px, 800px"
     alt="Students working on laptops in a classroom">

Here the browser compares the screen width against sizes, then picks the smallest file from srcset that is still sharp enough. The plain src remains as the fallback for older browsers.


8. Worked Example: Responsive Images with <picture>

The <picture> element wraps several <source> tags and one final <img>. It solves two different problems.

Problem one: modern file formats

Newer formats such as WebP compress better than older ones, which matches the standard performance advice to compress images and prefer modern formats. You serve WebP where it is understood and JPEG everywhere else:

<picture>
  <source srcset="course-banner.webp" type="image/webp">
  <img src="course-banner.jpg"
       alt="Banner advertising the web development course">
</picture>

The browser checks the first source; if it supports image/webp it downloads that file, otherwise it quietly uses the <img> fallback.

Problem two: art direction

Sometimes a wide photo works on desktop but a tighter crop is needed on a phone. The media attribute handles this:

<picture>
  <source srcset="hero-wide.jpg" media="(min-width: 800px)">
  <source srcset="hero-square.jpg">
  <img src="hero-square.jpg" alt="Instructor demonstrating code on screen">
</picture>

On a wide screen the browser picks hero-wide.jpg; on a narrow screen it takes the square crop. Note that the final <img> is mandatory — it is the fallback and also carries the alt text.


9. Worked Example: Adding Audio with <audio>

Audio follows the same pattern as video but is lighter and simpler. A minimal player:

<audio src="episode-01.mp3" controls></audio>

Without the controls attribute the player is invisible and the user has no way to start the sound, so in practice you almost always include it. A more realistic version offers several formats and fallback text:

<audio controls preload="metadata">
  <source src="episode-01.mp3" type="audio/mpeg">
  <source src="episode-01.ogg" type="audio/ogg">
  Your browser cannot play this episode. You can download it instead.
</audio>
  • The browser tries episode-01.mp3 first. MP3 support is universal in practice, so the Ogg source is a safety net rather than a necessity here.
  • preload="metadata" downloads just enough data to show the clip's length, without pulling the whole file until the listener presses play.
  • The plain text between the tags appears only if no source can be played at all.

10. Worked Example: Adding Video with <video>

Video is the richest media element. A sensible starting point:

<video controls width="640" height="360" poster="demo-cover.jpg" preload="metadata">
  <source src="product-demo.webm" type="video/webm">
  <source src="product-demo.mp4" type="video/mp4">
  Sorry, your browser does not support embedded video.
</video>

What each choice buys you:

  • Two sources cover the main formats: WebM is generally more efficient, and MP4 with the H.264 codec is the safe universal fallback. Listing WebM first means capable browsers download the smaller file.
  • The poster image shows before playback, so users see a meaningful frame instead of a black rectangle.
  • Fixed width and height reserve the player's space and stop the layout shifting while the file loads.

A common real-world pattern is a short, silent, looping clip behind a page heading:

<video autoplay muted loop playsinline width="1280" height="720" poster="office.jpg">
  <source src="office-loop.webm" type="video/webm">
  <source src="office-loop.mp4" type="video/mp4">
</video>

The muted attribute is essential here: since browsers block autoplay for media with sound, a muted clip is the only reliable way to play automatically. Users keep control through the browser's own pause options, or through the controls attribute if you add it.


11. Captions and Subtitles with <track>

Video and audio are unusable for some learners without text alternatives, and useful for everyone in noisy places. The <track> element adds timed text to a media element. Each track points to a WebVTT file — a plain-text format whose lines look like this:

WEBVTT

00:00:01.000 --> 00:00:04.000
Welcome to the HTML media lesson.

00:00:04.500 --> 00:00:08.000
Here we add a video element with captions.

The arrow between the two timestamps separates the start and end times, and each cue carries the text shown during that window. You attach the file with a <track> child inside the video:

<video controls width="640" height="360">
  <source src="lesson.mp4" type="video/mp4">
  <track src="lesson-en.vtt" kind="subtitles" srclang="en" label="English" default>
  <track src="lesson-hi.vtt" kind="subtitles" srclang="hi" label="Hindi">
  Your browser does not support embedded video.
</video>

The attributes matter:

  • kind — the purpose of the track: subtitles for translation of dialogue, captions for dialogue plus sound descriptions, descriptions for narration of the visuals, chapters for navigation.
  • srclang — the language of the track, required for subtitles.
  • label — the name shown in the player's track menu.
  • default — marks the track switched on when playback starts; only one track should have it.

12. Embedding Other Pages with <iframe>

An <iframe> (inline frame) embeds a complete HTML page inside your page. Video platforms, map services and form providers all distribute their content this way: they give you a snippet, and the snippet is an iframe pointing at their server.

<iframe src="https://www.example.com/embed/lesson"
        width="560" height="315"
        title="Lesson video player"
        loading="lazy"
        allowfullscreen></iframe>
  • src — the address of the page to embed.
  • title — describes the frame to screen readers; unlike images, iframes have no alt, so title is the accessibility hook.
  • loading="lazy" — defers loading until the frame scrolls into view, exactly as for images.
  • allowfullscreen — permits the embedded page to expand to full screen.

Two cautions. First, an iframe loads a whole second page with its own CSS and JavaScript, so a page full of iframes is heavy; lazy loading helps. Second, only embed content from services you trust, because the embedded page runs in front of your visitor. When a platform offers a copy-paste embed snippet, prefer their official snippet over hand-writing the URL.


13. Best Practices for HTML5 Media

Carry this checklist into every project that uses media:

  • Always provide text alternatives. Every <img> gets an alt; every iframe gets a title; every video with speech gets a <track>.
  • Reserve space. Set width and height so the page does not jump while media loads.
  • Compress and prefer modern formats. Large uncompressed images are the most common cause of slow pages; convert photos to WebP with a JPEG fallback via <picture>.
  • Lazy-load what is below the fold. Add loading="lazy" to images and iframes that are not visible when the page opens.
  • Offer multiple formats for audio and video. Use <source> with accurate type attributes so the browser can choose without guessing.
  • Never autoplay with sound. If playback must start automatically, mute the media first.
  • Use preload deliberately. metadata is a good default for players the user has not interacted with yet.
  • Host large videos sensibly. Embedding a dedicated platform's player is usually better than self-hosting huge files.

These habits carry straight into your later work: the React components you build will render media through these very tags and attributes, so every rule you internalise now pays off twice.

14. Sizing and Styling Media Responsively

HTML attributes give media an initial size, but CSS is what keeps media looking correct on every screen. The single most useful rule for any media-heavy page is this one:

img,
video,
iframe {
  max-width: 100%;
  height: auto;
}

Here is what happens. max-width: 100% says the element may never grow wider than its container, so a 1200-pixel-wide photo shrinks to fit a 360-pixel phone screen instead of overflowing. height: auto keeps the proportions correct while the width shrinks, so the picture never looks squashed or stretched.

Without this rule, a fixed width="960" video on a small phone either overflows sideways or (with a percentage width alone) loses its shape. With it, one short stylesheet handles every device.

For iframes there is an extra trick, because an iframe with height: auto collapses to a thin strip — the browser cannot guess the proportions of someone else's page. The modern solution is the aspect-ratio property:

iframe {
  width: 100%;
  aspect-ratio: 16 / 9;
}

This tells the browser to keep a 16:9 shape at whatever width the frame ends up, which matches the shape most embedded video players use. You can apply the same idea to video elements you have sized with attributes.

  • Use HTML width and height attributes to declare the natural size — the browser uses them to reserve space before the file loads.
  • Use CSS max-width: 100% and height: auto to let media shrink on small screens.
  • Use aspect-ratio on iframes so embedded content keeps a sensible shape.

15. Controlling Playback with JavaScript

The built-in controls attribute is enough for most pages, but real products often need custom players: a play button styled to match the brand, a "skip intro" link, or a progress readout. Every media element exposes methods and events that JavaScript can use, and this is the bridge between this sub-module and the later DOM module of your course.

The key methods are play(), pause() and setting the currentTime property. The key events are play, pause, ended, timeupdate and loadedmetadata.

A small custom play/pause toggle looks like this:

<video id="lesson" src="lesson.mp4" width="640" height="360"></video>
<button id="toggle">Play</button>

<script>
  const player = document.querySelector("#lesson");
  const toggle = document.querySelector("#toggle");

  toggle.addEventListener("click", () => {
    if (player.paused) {
      player.play();
    } else {
      player.pause();
    }
  });

  player.addEventListener("play", () => {
    toggle.textContent = "Pause";
  });

  player.addEventListener("pause", () => {
    toggle.textContent = "Play";
  });
</script>

Reading the example step by step:

  1. document.querySelector grabs the video and the button from the page.
  2. Clicking the button checks the video's paused property and calls the matching method.
  3. The play and pause events keep the button label in sync even when the user controls playback through the keyboard or the native controls.

A slightly richer example shows the current playback position, updated several times a second by the timeupdate event:

const player = document.querySelector("#lesson");
const readout = document.querySelector("#time");

player.addEventListener("timeupdate", () => {
  readout.textContent = player.currentTime.toFixed(1) + " seconds";
});

You do not need to master this now — the DOM module covers events in depth. What matters here is that <video> and <audio> are not black boxes: they are elements with a scriptable surface, which is exactly what React media components build on.


16. Lazy Loading and Performance for Media-Heavy Pages

Images and video dominate the download weight of a typical page. A gallery of twenty uncompressed photographs can easily outweigh all the HTML, CSS and JavaScript combined. The research behind modern frontend practice says the same thing in React terms: compress images, prefer modern formats such as WebP, and load assets dynamically. The HTML tools for this are simple and worth memorising.

  • Lazy-load everything below the first screen. Add loading="lazy" to images and iframes that the visitor will only see after scrolling. Above-the-fold images, such as a hero banner, should stay eager so they appear instantly.
  • Set preload thoughtfully on players. preload="metadata" downloads just the file's duration and dimensions, so the player looks ready without pulling megabytes. Reserve preload="auto" for media the user is almost certain to play.
  • Choose efficient formats. WebP typically produces much smaller files than older image formats at similar quality. Serve it through <picture> with a fallback.
  • Resize before upload. Serving a 4000-pixel photo into a 400-pixel slot wastes most of the download. Export images at roughly the size they are displayed.
  • Prefer embedding for long videos. A dedicated video platform handles compression, adaptive quality and playback devices for you; self-hosting large video files rarely pays off for a learning project.

A quick comparison of loading strategies:

SituationRecommended markupWhy
Hero image visible on page openPlain <img>, no loading attributeMust appear immediately; lazy loading would delay it
Images further down a long articleloading="lazy"Downloads only when the reader approaches them
Embedded player below the foldIframe with loading="lazy"Skips loading a whole second page until needed
Audio or video player the user may skippreload="metadata"Shows duration without downloading the full file
Short muted background clipautoplay muted loop playsinlinePlays automatically and silently, as browsers permit

17. Common Media Mistakes and How to Fix Them

Most media problems on real pages come from a handful of repeat offences. Each row below names the mistake, explains the damage, and shows the correction:

MistakeWhy it hurtsCorrect way
Writing <img src="photo.jpg"> with no altScreen readers announce nothing; search engines get no descriptionAdd meaningful text: alt="Students at a coding workshop", or alt="" for purely decorative images
Omitting width and heightThe page jumps as images load, which is unpleasant and hurts perceived speedDeclare both attributes so the browser reserves the box in advance
Using autoplay with soundBrowsers block it, so nothing happens; when it does play, users hate itAdd muted alongside autoplay, plus playsinline on video
A single src on <video> with no <source> listOne format failure means no playback at allList WebM first, then MP4, each with an accurate type
Wrong or missing type on <source>The browser cannot skip unsupported files without downloading themWrite exact MIME types such as type="video/mp4" or type="image/webp"
An iframe with no titleAssistive technology announces "frame" with no clue about its contentAdd title="Lesson video player" or a similar label
preload="auto" on every playerVisitors download large files they never playDefault to preload="metadata" unless playback is near-certain
Uploading huge, unoptimised imagesSlow pages on mobile data, which is how most of your audience will visitCompress, resize to display size, and serve WebP with a fallback
Forgetting controls on <audio>The player is invisible and cannot be started by anyoneAlways include controls unless you build a full custom player
Fixed pixel widths on media without responsive CSSContent overflows on phonesApply max-width: 100%; height: auto; globally

18. Accessibility for Media: Going Beyond the Basics

Part of accessibility was covered already — alt text and <track> captions. Two further habits complete the picture for this sub-module.

Describe the purpose, not the appearance

A good alt value answers the question "why is this image here?" rather than "what does it look like?". Compare:

<!-- Weak: describes pixels -->
<img src="chart.png" alt="Bar chart">

<!-- Strong: describes meaning -->
<img src="chart.png" alt="Bar chart showing enrolment doubling after the course redesign">

Give every control a text alternative

If you build a custom play button with only an icon inside, a screen reader user hears an unnamed button. Put visible or hidden text inside it:

<button id="toggle">Play lesson video</button>

Respect reduced motion

Some users set their device to minimise movement, and a looping background video can be unpleasant for them. The CSS media query prefers-reduced-motion lets you pause or hide decorative motion for those users; simply knowing the option exists is enough at this stage, and it returns in the CSS animations sub-module.

Do not rely on colour or sound alone

If an audio clip carries essential information, make sure the same information exists as text on the page — a transcript beside the player is the simplest pattern, and it also helps users in quiet offices and on slow connections.


19. Choosing the Right Media Element: A Decision Table

When you face a real requirement, this table walks you from the need to the element:

If you need to…UseKey attributes or children
Show one photograph or illustration<img>src, alt, width, height, loading
Serve WebP with a JPEG fallback<picture> with <source type="image/webp">srcset, type, final <img>
Show different crops per screen size<picture> with media sourcesmedia="(min-width: 800px)"
Let one image file adapt to screen density<img srcset … sizes>srcset, sizes
Play a podcast or sound clip<audio>controls, preload, <source>
Play a lesson video with captions<video> with <track>controls, poster, preload
Run a silent background clip<video>autoplay muted loop playsinline
Embed a map or another site's player<iframe>src, title, loading, allowfullscreen
Show a PDF inside the page<iframe> or <object>src or data, plus a link fallback

20. Practical Project: Building a Course Lesson Page

You will now build a complete lesson page that uses every core media element in a realistic arrangement: a hero banner, a captioned video, an audio recap and an embedded frame. The project takes about an hour and produces a page you can extend in later modules.

Step 1: Create the file structure

Make a folder named lesson-page with this layout:

lesson-page/
  index.html
  styles.css
  media/
    hero.jpg
    hero.webp
    lesson.mp4
    lesson.webm
    lesson-cover.jpg
    lesson-en.vtt
    recap.mp3

If you do not have real files yet, any images, a short video and an MP3 from your own device will do; the file names just have to match.

Step 2: Write the HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Lesson: HTML5 Media</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <header>
    <h1>Lesson: Working with Media</h1>
    <picture>
      <source srcset="media/hero.webp" type="image/webp">
      <img src="media/hero.jpg"
           alt="Laptop and headphones on a desk, ready for a video lesson"
           width="1200" height="400">
    </picture>
  </header>

  <main>
    <section>
      <h2>Watch the lesson</h2>
      <video controls width="960" height="540"
             poster="media/lesson-cover.jpg" preload="metadata">
        <source src="media/lesson.webm" type="video/webm">
        <source src="media/lesson.mp4" type="video/mp4">
        <track src="media/lesson-en.vtt" kind="subtitles"
               srclang="en" label="English" default>
        Sorry, your browser does not support embedded video.
      </video>
    </section>

    <section>
      <h2>Listen to the recap</h2>
      <p>Prefer audio? Here is a two-minute summary of the lesson.</p>
      <audio controls preload="metadata">
        <source src="media/recap.mp3" type="audio/mpeg">
        Your browser cannot play this audio clip.
      </audio>
    </section>

    <section>
      <h2>Extra resource</h2>
      <iframe src="https://www.example.com/embed/replace-with-your-embed-url"
              width="560" height="315"
              title="Supplementary video player"
              loading="lazy" allowfullscreen></iframe>
    </section>
  </main>
</body>
</html>

Replace the iframe address with a real embed snippet from a service you use, keeping the title and loading attributes intact.

Step 3: Write the stylesheet

body {
  font-family: Arial, sans-serif;
  margin: 0 auto;
  max-width: 960px;
  padding: 1rem;
}

img,
video,
iframe {
  max-width: 100%;
  height: auto;
}

iframe {
  aspect-ratio: 16 / 9;
}

section {
  margin-top: 2rem;
}

Step 4: Test the page

  1. Open index.html in a browser and confirm the hero image appears and the video shows its poster frame.
  2. Play the video and switch on the caption track from the player menu.
  3. Narrow the browser window: every media element should shrink without overflowing or distorting.
  4. Check the audio player shows a duration (proof that preload="metadata" worked) before you press play.
  5. Temporarily rename lesson.mp4 and confirm the fallback text appears when no source can load — a quick way to see fallback behaviour for yourself.

Step 5: Extend it

Good next moves, each building on one concept from this sub-module: add srcset with three image sizes to the hero, add a second <track> in another language, or wrap the video in a figure with a caption using the semantic tags from the next sub-module.


21. Practice Exercises

  1. Write an <img> tag for a photo named festival.jpg that is 1000 by 600 pixels, with meaningful alt text and lazy loading.
  2. Build a <picture> block that serves team.webp where supported and team.jpg otherwise.
  3. Create an <img> using srcset with files at 400, 800 and 1600 pixels wide, and write a sizes attribute that requests 400 pixels on screens up to 600 pixels wide and 800 pixels above that.
  4. Write an <audio> element offering MP3 and Ogg sources, with preload="metadata" and fallback text.
  5. Write a <video> element that autoplays silently, loops, never forces full screen on phones, and still offers native controls.
  6. Attach two subtitle tracks to a video — English and Hindi — with the English one active by default.
  7. Write an iframe for an embedded player with a proper title, lazy loading and allowfullscreen.
  8. Find the mistake: <video src="clip.mp4" autoplay></video> — rewrite it so autoplay reliably works, and explain each attribute you added.
  9. Explain in one sentence each why alt="" can be correct, and when you must never leave alt text empty.
  10. Write the two-line CSS rule that makes all images, videos and iframes shrink gracefully on small screens.

22. Interview Questions and Answers

What is the difference between <img> and <picture>?

<img> displays a single file chosen by the author. <picture> is a container that holds several <source> candidates plus one final <img>; the browser picks the first source whose type it supports or whose media condition matches the screen. Use <picture> for format switching or art direction; use plain <img> when one file is enough.

What do srcset and sizes do?

srcset lists multiple versions of the same image with their widths, and sizes tells the browser how wide the image will be rendered under different screen conditions. The browser combines both to download the smallest file that still looks sharp, saving data on small screens. The plain src acts as the fallback.

How does the type attribute on <source> help?

It declares the file's MIME type, such as video/webm or image/webp. The browser checks this before downloading, so it skips formats it cannot play instead of wasting a request. Without it, the browser may have to download a file just to discover it cannot use it.

What does the preload attribute control?

It hints how much of an audio or video file to download before playback starts. none downloads nothing until the user plays, metadata fetches only duration and dimensions, and auto lets the browser download what it thinks is needed. It is a hint, not a command — browsers may ignore it on mobile networks.

Why does autoplay often fail, and what is the fix?

Browsers block autoplay for media with sound to protect users from unexpected noise. The reliable pattern for genuine autoplay needs is autoplay muted loop playsinline: muted media is allowed to start automatically, and playsinline stops phones from taking over the whole screen. For anything with sound, let the user start playback.

What is the poster attribute for?

It supplies an image shown in the video player before playback begins. Without it the user sees the first decoded frame or a blank area; with it they see a chosen cover image, which also makes the player look intentional while the file loads.

How do you add captions to a video?

Place <track> children inside the <video> element, each pointing to a WebVTT file with a kind such as subtitles, a srclang, a label for the player menu, and optionally default to preselect one. The VTT file contains timed cues with start and end timestamps and their text.

When is an empty alt attribute correct?

When an image is purely decorative and carries no information — background flourishes, spacer graphics, repeated icons next to visible text. An empty alt="" tells assistive technology to skip the image entirely. Omitting the attribute is different and wrong: the image may be announced by its file name.

What is the difference between <iframe>, <embed> and <object>?

<iframe> embeds a full HTML document and is the standard way to include maps, widgets and external players. <embed> and <object> are older general-purpose containers for external content such as PDFs or plugin-era resources; they still work but have no dedicated fallback content model like the text inside <video>. In day-to-day work you will almost always reach for <iframe>.

How do you prevent layout shift when media loads?

Declare width and height attributes so the browser reserves the correct box before the file arrives, and keep the responsive pair max-width: 100%; height: auto; in CSS. For iframes, set an explicit aspect-ratio. The reserved space means surrounding text does not jump when the media appears.

How would you serve WebP images while keeping older browsers working?

Wrap the image in <picture>, add a <source srcset="file.webp" type="image/webp"> first, and keep a normal <img src="file.jpg"> as the final fallback. Browsers that understand WebP take the source; the rest silently use the JPEG. No JavaScript is involved.

Why does a media-heavy page slow down, and what markup fixes it?

Media files are usually the largest payloads on a page. The fixes are markup-level: compress and resize images before upload, prefer efficient formats such as WebP through <picture>, add loading="lazy" to below-the-fold images and iframes, use preload="metadata" on players, and embed long videos through a dedicated platform rather than self-hosting them.


23. Quick Revision Checklist

  • Media elements come in two shapes: self-closing (<img>, <source>, <track>) and containers with fallback content (<video>, <audio>, <picture>).
  • Every image needs alt — meaningful text for informative images, empty text for decorative ones.
  • Always set width and height to stop layout shift, and add global CSS max-width: 100%; height: auto;.
  • <picture> solves format switching (type) and art direction (media); srcset/sizes on <img> solve resolution switching.
  • List multiple <source> children with accurate MIME types; the browser takes the first one it can play.
  • Reliable autoplay is always autoplay muted loop playsinline.
  • preload="metadata" is the sensible default for players; poster gives video a cover image.
  • <track> plus a WebVTT file adds captions; kind, srclang, label and default configure it.
  • Iframes embed other pages; give them title, loading="lazy" and an aspect-ratio in CSS.
  • Compress and resize images, prefer WebP, and lazy-load anything below the first screen.

24. Official Documentation and Further Reading

This sub-module sits at the foundation of your React training, and the performance habits you practised here — compressed images, modern formats, dynamic loading of heavy assets — reappear throughout React work. These readings from your course resource list connect the two:


Conclusion

Media is where a page stops being a document and starts being an experience. In this sub-module you moved from a bare <img> tag to a complete lesson page containing a responsive hero, a captioned video with multiple formats, an audio recap and an embedded frame — and, more importantly, you learned the reasoning behind every attribute: alt for meaning, dimensions for stability, <source> for compatibility, <track> for inclusion, loading and preload for speed, and muted for autoplay that actually works.

Keep the decision table and the mistakes table close at hand while you practise. The same tags, attributes and habits will surface again inside React components, where you will render media through JSX and wire it to state and events — so the effort you invest in getting this foundation right now is effort you will not have to repeat later.

Learn more in the React JS Training course, or register for a course demo.

Previous Next
whatsapp