Search code examples
htmlcssresponsive-designoverlaymix-blend-mode

How do use mix-blend-mode with the color of my choice to overlay text on a video?


I need my text to be transparent towards the video behind it but not the background of the text.

<main>
    <div class="container">
        <video
            src="./pexels-tima-miroshnichenko-5377684.mp4"
            autoplay
            muted
            loop
        ></video>
        <h2>Hello There!</h2>
    </div>
</main>


main {
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

.container {
    width: 60%;
    height: fit-content;
    overflow: hidden;
    display: grid;
}

video,
h2 {
    grid-column: 1;
    grid-row: 1;
    width: 100%;
    display: inline;
}

.container h2 {
    margin: 0;
    height: 100%;
    background: #ffdb99;
    font-size: 13vw;
    padding: 0;
    color: #fff;
    text-align: center;
    text-transform: uppercase;
    z-index: 2;
    mix-blend-mode: screen;
    font-family: 'Poppins', sans-serif;
}

This is the result: image of text/video overlay

I need the background to stay opaque but the text to be transparent towards the video behind it!

Thanks for your input in advance!! Hope my question is clear!


Solution

  • I do not know how to do this with mix-blend-mode as you can't have a video as a background in the normal CSS sense.

    But you can achieve the effect by 'cutting text holes' in the background and overlaying the whole thing over the video using SVG mask.

    Here's an example, you can choose the color as it is not affected by any blending or masking:

    * {
      margin: 0;
      padding: 0;
    }
    
    video {
      width: 100%;
      height: auto;
      z-index: -1;
      position: relative;
      top: 50%;
      transform: translateY(-50%);
    }
    
    svg {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    
    text {
      font-size: 10vmin;
      text-anchor: middle;
      font-family: sans-serif;
    }
    <video src="https://www.w3schools.com/html/mov_bbb.mp4" autoplay muted loop></video>
    <svg width="33vw" height="33vh">
      <mask id="mask" height="100%" width="100%">
        <rect x="0" y="0" width="100%" height="100%" fill="#fff"></rect>
        <text>
          <tspan x="50%" dy="1.2em">HELLO</tspan>
          <tspan x="47%" dy="1em">THERE!</tspan>
        </text>
      </mask>
      <rect width="100%" height="100%" mask="url(#mask)" fill="#ffdb99"></rect>
    </svg>