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

房东的猫 提交于 2021-02-10 14:53:24

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/62640346/how-to-apply-a-mask-image-only-on-an-elements-background-and-not-on-its-childre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!