htmlcsssvg

How to create a text mask with a reverse color of the SVG background using CSS?


I have an SVG image as the background-image for the footer of my webpage. The logo text appears over this background, and its color needs to adapt to the background's light or dark sections.

On large screens, the logo text falls entirely on the white part of the background, so a black text works fine. On mobile screens, it appears over the dark part of the image, so I switch the text color to white, which also works. The issue arises with intermediate screen sizes, where the logo text might overlap both light and dark areas of the background. This causes parts of the text to blend into the background, making it unreadable.

I would like to create a solution where the SVG acts as a mask for the text, automatically changing the logo text color (e.g., from black to white) based on the background it overlaps. How can I achieve this effect?

What are some effective techniques or CSS properties that would help solve this issue?

Here is a simple fiddle, the SVG is set as background-image in the original code.

I have tried to use something like mix-blend-mode but it's not what I am looking for:

      footer {
        background-image: url("../assets/images/mountains.svg");
        z-index: 0;
      }
    
      .logo {
        position: relative;
        z-index: 1;
      }
    
      .logo::after {
        position: absolute;
        content: "Relaps";
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: -1;
        color: white;
        mix-blend-mode: difference;
      }

This is what I would archieve:

enter image description here


Solution

  • mix-blend-mode: difference should work fine, but the overlay needs to be opaque (monochrome black and white in this case) due to how alpha blending works with these blend modes.

    Please excuse the poor linear gradient excuse for a forestscape.

    #a {
      width: 400px;
      height: 150px;
      background: linear-gradient(22deg, #111 0 50%, white 50% 100%);
      font-size: 40pt;
    }
    #a h1 {
      background: #000;
      color: #fff;
      mix-blend-mode: difference;
    }
    <div id="a">
      <h1>Relaps</h1>
    </div>