CSS3 遮罩
大约 2 分钟
CSS3 遮罩
文章内容
- CSS3 遮罩介绍
- 遮罩各属性介绍
CSS3 遮罩介绍
CSS mask 属性历史悠久,最早出现在 Safari 浏览器上。如今,除了 IE,大多数现代浏览器都支持 CSS3 mask 属性。

快速入门示例
准备两张图片:
zelda.jpg (JPG)

mask.png (PNG, 透明背景)

示例代码
<div class="mask"></div>* {
margin: 0;
padding: 0;
}
div {
width: 1200px;
height: 600px;
outline: 1px solid;
margin: 50px auto;
background: url('./zelda.jpg') no-repeat center/cover;
}
.mask {
-webkit-mask-image: url('./mask.png');
}效果:遮罩图片透明部分不显示底图,非透明部分显示底图。

渐变遮罩
.mask {
-webkit-mask-image: linear-gradient(transparent 10%, white);
}效果:线性透明渐变。

遮罩各属性介绍
mask-image
设置遮罩图片或渐变。默认值为 none。
mask-repeat
控制遮罩层重复行为。默认值为 repeat。
.mask {
-webkit-mask-image: url('./mask.png');
-webkit-mask-repeat: no-repeat;
}mask-position
设置遮罩层位置。默认值为 0 0。
.mask {
-webkit-mask-image: url('./mask.png');
-webkit-mask-repeat: no-repeat;
-webkit-mask-position: center;
}mask-size
设置遮罩层大小。默认值为 auto。
.mask {
-webkit-mask-image: url('./mask.png');
-webkit-mask-repeat: no-repeat;
-webkit-mask-position: center;
-webkit-mask-size: contain;
}mask-origin
设置遮罩层的定位区域。默认值为 border-box。
.mask {
-webkit-mask-image: url('./mask.png');
-webkit-mask-repeat: no-repeat;
-webkit-mask-origin: content-box;
}mask-clip
设置遮罩层的裁剪区域。默认值为 border-box。
.mask {
-webkit-mask-image: url('./mask.png');
-webkit-mask-repeat: no-repeat;
-webkit-mask-clip: content-box;
}mask-mode
设置遮罩模式。默认值为 match-source。Firefox 支持,Chrome 可用 mask-source-type 替代。
.mask {
-webkit-mask-image: url('./mask2.jpg');
-webkit-mask-repeat: no-repeat;
-webkit-mask-position: center;
mask-mode: luminance;
}mask-type
仅作用于 SVG 元素,设置遮罩模式。默认值为 luminance。
mask-type: alpha;mask-composite
设置多张遮罩图片的合成方式。默认值为 add。
- add:遮罩累加
- subtract:遮罩相减
- intersect:遮罩相交
- exclude:遮罩排除
