cssclip-pathcss-mask

Use a dynamically expanding div as clipping mask for background image in parent


I'm looking for a CSS solution that adapts to div contents, with the functionality of clip-path but dynamic. This is my code:

.background {
  background: yellow;
  text-align: center;
}

.text {
  display: inline-block;
  margin: 20px;
  padding: 20px;
  background: teal;
}
<div class="background">
<div class="text">
My text is in here
</div>
</div>

Yellow and teal are just used for illustration. I want to replace the yellow background with an image, but only show it in the teal area. The div.background spans the width of the browser, but I cannot make assumptions about the width of div.text. Can this be done with only CSS or does it require JS and dynamically setting background-position?


Solution

  • Use a pseudo element that you make relative to the background element

    .background {
      background: yellow;
      text-align: center;
      position: relative;
      z-index: 0;
    }
    
    .text {
      display: inline-block;
      color: #fff;
      margin: 20px;
      padding: 20px;
      clip-path: inset(0); /* clip to only text element */
    }
    
    .text:before {
      content: "";
      position: absolute;
      z-index: -1;
      inset: 0;
      background: url(https://picsum.photos/id/1056/800/600) center/cover;
    }
    
    /* to illustrate */
    .text:hover {
      clip-path: none;
    }
    <div class="background">
      <div class="text">
        My text is in here
      </div>
    </div>