Search code examples
htmlcsshtml5-video

Wrapping text overlayed on HTML video


I'm trying to overlay text on top of a video element. My code so far is:

body {
  margin: auto;
  text-align: center;
  background-color: black;
  line-height: 0;
}

.container {
  position: relative;
  display: grid;
  height: 100%;
}

.container video {
  max-width: 100%;
  max-height: 100vh;
  margin: auto;
  width: 100%;
  height: auto;
  position: relative;
  z-index: 0;
}

.overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 8vw;
  font-family: Arial, Sans-Serif;
  opacity: 25%;
  z-index: 1;
}
<div class="container">
  <video type="video/mp4" src='data:video/mp4;base64,...'>Your browser does not support the video tag.</video>
  <div class="overlay">
    <p>OVERLAY TEXT</p>
  </div>
</div>

This works perfectly. However, the only issue is that when the overlay text gets too long, it doesn't wrap onto the next line, instead it stacks on top of itself. Is there a way to style this so that the overlay text wraps onto the next line and the whole overlay remains centered over the video? Thanks!


Solution

  • Since you're using Grid, you don't need the absolute positioning:

    body {
      margin: auto;
      text-align: center;
      background-color: black;
      line-height: 0;
    }
    
    .container {
      display: grid;
      grid-template-areas: "video";
      place-items: center;
    }
    
    .container video {
      max-width: 100%;
      max-height: 100vh;
      margin: auto;
      width: 100%;
      height: auto;
      grid-area: video;
    }
    
    .overlay {
      grid-area: video;
      color: white;
      font-size: 8vw;
      font-family: Arial, Sans-Serif;
      opacity: 25%;
    }
    <div class="container">
      <video type="video/mp4" src='data:video/mp4;base64,...'>Your browser does not support the video tag.</video>
      <div class="overlay">
        <p>OVERLAY TEXT</p>
      </div>
    </div>