Search code examples
htmlcsscolors

Using text as a mask to invert the colours of anything behind it


I am working out a page that will have a quick-paced shuffle of images on one side, and would like to put bold and visually-attractive text that will lay over a corner of it as a mask and invert the colours of whatever is behind it. Are there any ways to style the text to do this in css?

I haven't been able to find any common solutions or workarounds for what I'm looking to achieve, only how to invert a selected colour.


Solution

  • This should work. mix-blend-mode: difference; makes the trick. I attached a working snippet.

    .container {
      position: relative;
      height: 300px;
      width: 400px;
      display: flex;
    }
    
    .color-1 {
      width: 33%;
      background-color: red;
    }
    
    .color-2 {
      width: 33%;
      background-color: violet;
    }
    
    .image {
      width: 33%;
      background-image: url(https://picsum.photos/200/300);
    }
    
    p {
     margin: 0;
     width: 100%;
     position: absolute;
     font-family: 'Helvetica', sans-serif;
     font-weight: 600;
     text-align: center;
     font-size: 50px;
     top: 100px;
     left: 0;
     right: 0;
     color: white;
     mix-blend-mode: difference;
    }
    <div class="container">
      <div class="color-1"></div>
      <div class="color-2"></div>
      <div class="image"></div>
      <p>Inverting Text</p>
    </div>