How to Add Subtitles to HTML5 Videos

HTML5 brought with itself major changes to accommodate the new web. It natively supports video element among a host of other things.

These medias can be enjoyed by everyone irrespective of the language through the use of subtitles and this tutorial shows how it can be done.

Adding Subtitles with <track> Element

The subtitle files are added to a video using the <track> tag. This element is defined within the video element itself.

The <track> element has the following attributes :

  • kind : Specifies the type of the text track. Allowed values are captions, chapters, descriptions, >metadata and subtitles
  • label : Specifies the title of the track
  • src : Path or url of the track file
  • srclang : Specifies the language of the track
  • default : Incase multiple subtitle files are included, this attribute specifies the default file to be used

The <track> tag is implemented as shown below :

<video id="my-video-stream" width="1280" height="720" controls>
    <source src="vid/vid.mp4" type="video/mp4">
    <track label="English" kind="subtitles" src="sub/vid_sub.vtt" srclang="en">
</video>

HTML5 supports Web Video Text Track (vtt) format. The popular srt files are not supported. You can converrt srt files to vtt files using this online converter.

Adding Multiple Subtitles

Multiple subtitles can be added to the video by defining multiple <track> tags within the video tag. The subtitles will show up with the value as defined in the label attribute.

<video id="my-video-stream" width="1280" height="720" controls>
    <source src="vid/vid.mp4" type="video/mp4">
    <track label="English" kind="subtitles" src="sub/vid_sub_en.vtt" srclang="en">
    <track label="French" kind="subtitles" src="sub/vid_sub_fr.vtt" srclang="fr">
</video>

The subtitles will show in the video player as shown below :

Note the names of the subtitles in video player is from the label attribute.

Styling Subtitles with CSS

The subtitle text can be styled with CSS using the ::cue pseudo-element. The background of the subtitle text or the color of the text or its size or the font can be modified using simple CSS declarations.

#my-video-stream::cue {
    background-color: transparent;
    color: #FFF;
    font-size: 32px;
    font-family: "Lobster", cursive;
}

The following image shows the subtitle text in Lobster font, imported from Google Fonts.

Useful Resources

How to Add Preview Image to a HTML Video
Detecting Change in Playing Subtitles Text for 〈video〉Element
Loading Comments