How to apply a mask-image only on an element's background and not on its children?
Asked Answered
H

1

6

I'm trying to apply a mask-image on the background of an element, but I don't want to mask its children. I've tried to change the z-index without any success.

* {
  box-sizing: border-box;
}
body {
  margin: 0;
  background: #000;
}
.el {
  width: 100%;
  height: 60px;
  mask-repeat: no-repeat;
  mask-position: center;
  background-color: #fff;
    -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 60'%3E%3Cpath d='M100 60c-13.43 0-20.2-11.37-26.74-22.37C67.25 27.53 61.57 18 50 18s-17.25 9.54-23.26 19.63C20.2 48.63 13.43 60 0 60V0h100z'/%3E%3C/svg%3E");
    -webkit-mask-repeat: repeat-x;
    -webkit-mask-position: left bottom;
    z-index: 10;
}
.el p {
  position: relative;
  z-index 99;
  text-align: center;
  padding-top: 20px;
  width:400px;
  margin: auto;
  background: red;
  color: white;  
}
<div class="el"><p>Duis enim elit, porttitor id feugiat at, blandit at erat. Proin varius libero sit amet tortor volutpat diam laoreet.</p></div>

As you can see on my Codepen: https://codepen.io/marc-tison/pen/jOWGaYe, the red box is masked.

Is there a solution to prevent this?

Hootman answered 29/6, 2020 at 14:28 Comment(0)
G
6

Use it inside a pseudo element:

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  background: #000;
}

.el {
  position: relative;
  z-index: 0;
}

.el:before {
  content: "";
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: #fff;
  -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 60'%3E%3Cpath d='M100 60c-13.43 0-20.2-11.37-26.74-22.37C67.25 27.53 61.57 18 50 18s-17.25 9.54-23.26 19.63C20.2 48.63 13.43 60 0 60V0h100z'/%3E%3C/svg%3E");
          mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 60'%3E%3Cpath d='M100 60c-13.43 0-20.2-11.37-26.74-22.37C67.25 27.53 61.57 18 50 18s-17.25 9.54-23.26 19.63C20.2 48.63 13.43 60 0 60V0h100z'/%3E%3C/svg%3E");
}

.el p {
  text-align: center;
  padding-top: 20px;
  width: 400px;
  margin: auto;
  background: red;
  color: white;
}
<div class="el">
  <p>Duis enim elit, porttitor id feugiat at, blandit at erat. Proin varius libero sit amet tortor volutpat diam laoreet.</p>
</div>
Gun answered 29/6, 2020 at 14:47 Comment(4)
Thanks for the solution! Is there a way to achieve this without using pseudo element?Hootman
@MarcDuluc no, you need an extra element because mask will apply to the element and all its content so you cannot disable this and you have to apply it to an extra element with no content. Is there any issue with the use of pseudo element?Gun
Thanks for the explanation. I've got a weird case where I can't use a pseudo element.Hootman
@MarcDuluc I am pretty sure you can, show your caseGun

© 2022 - 2024 — McMap. All rights reserved.