Search code examples
csshtml5-videowebvtt

Positioning all subtitles of a vtt file over video rather than positioning cue by cue


I want all .vtt subtitles to be lifted upwards over my htmlVideoElement a bit because they are too low down in the video viewport. I've read loads of articles and they all use the same example which doesn't solve my problem. I can position individual cues as follows

2
00:00:18.166 --> 00:00:20.083 line:70%
At the right we can see the...

But I don't want to have to add line:70% to a hundred cues, I want to style all cues globally. The following code changes the text colour and background for all cues but none of the attempts to reposition the subtitles work with this.

WEBVTT

STYLE
::cue {
  background-image: linear-gradient(to bottom, dimgray, lightgray);
  color: green;
  line:70%;
  position: 70%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Solution

  • If you could add some JavaScript code, then you should try method below:

    1 Add event handler:

    const track = this.video.textTracks[0] //you should choose you text track
    track.addEventListener('cuechange', onCueChange);
    

    2 Update the properties of your cues:

    function onCueChange(event) {
      const cues = event.currentTarget.cues;
      for (let i = 0; i < cues.length; i++) {
        cues[i].line = 0 
      }     
    }
    

    Here's the code block

     window.onload = function() {
      let video = document.querySelector('video');
      const track = video.textTracks[0] //you should choose you text track
      track.addEventListener('cuechange', onCueChange);
    
      function onCueChange(event) {
        const cues = event.currentTarget.cues;
        for (let i = 0; i < cues.length; i++) {
          cues[i].line = 0 
        }       
      }
    }