Search code examples
htmlcssbackground-imagemask

Make Div Mask Background Image to Match Parent Background Image


I am trying to accomplish an effect where it looks like the "container" div is inverting the background image of the "parent" div. From my research I can't seem to find a way other than the "parent" and the "container" being the same size with different backgrounds, and the "content" div masking the "container" div. Here is an image of what I would like it to look like.

enter image description here

Here is my HTML:

<div class="parent">
  <div class="container">
    <div class="content">
    </div>
  </div>
</div>

The "parent" div has a normal background, while the "container" div (same size as "parent") has an inverted version of the "parent" background (inverted via thrid party program, I am not trying to invert it via css).

My question is, what CSS do I need to apply to the "content" and "container" div to achieve a mask where the "container" div's background is only shown through the "content" div?


Solution

  • An idea is to play with background-clip and adjust padding to control how much background you will show from the inner container:

    .container {
      height: 300px;
      background: url(https://picsum.photos/1000/800?image=1069) center/cover;
    }
    
    .content {
      height: 100%;
      background: url(https://picsum.photos/g/1000/800?image=1069) center/cover;
      background-clip: content-box;
      padding: 100px calc(100% - 300px) 100px 50px;
      box-sizing: border-box;
    }
    <div class="container">
      <div class="content">
        Some text
      </div>
    </div>

    This can also be done with one container and multiple backgrounds:

    .container {
     height:300px;
     background:
        url(https://picsum.photos/g/1000/800?image=1069) center/cover,
        url(https://picsum.photos/1000/800?image=1069) center/cover;
      background-clip:
        content-box,
        padding-box;
      padding:100px calc(100% - 300px) 100px 50px;
      box-sizing:border-box;
    }
    <div class="container">
        Some text
    </div>