如何仅在元素的背景而不是其子元素上应用遮罩图像?

时间:2020-06-29 14:28:20

标签: css svg background css-mask

我正在尝试在元素的背景上应用遮罩图像,但是我不想遮罩其子元素。我试图更改z索引没有成功。

* {
  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>

如您在我的Codepen上看到的:https://codepen.io/marc-tison/pen/jOWGaYe,红色框被遮盖了。

是否有防止这种情况的解决方案?

1 个答案:

答案 0 :(得分:0)

在伪元素中使用它:

import SwiftUI

private func clamp<T: Comparable>(_ value: T, range: ClosedRange<T>) -> T {
    max(min(value, range.upperBound), range.lowerBound)
}

private func eligibleDateRange() -> ClosedRange<Date> {
    let now = Date()
    let start = Calendar.current.date(byAdding: .minute, value: 60, to: now)!
    let end = Calendar.current.date(byAdding: .day, value: +7, to: now)!
    return start...end
}

struct ContentView: View {
    @State private var selectedDate = clamp(Date(), range: eligibleDateRange())
    var body: some View {
        VStack {
            DatePicker(selection: $selectedDate, in: eligibleDateRange()) {
                Text("")
            }
            Button(action: {
                print(self.selectedDate.description(with: .current))
            }) {
                Text("Continue")
            }
        }
     }
}

* {
  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;
}

相关问题