使用CSS伪元素、background叠加或mask-image可实现图片渐变蒙版。伪元素通过绝对定位叠加渐变层,适合内容图片;background将渐变与图片结合,适用于背景图;mask-image支持精细透明控制,需注意-webkit-前缀兼容性。

在网页设计中,给图片添加渐变蒙版可以增强视觉层次感,突出文字内容或实现美观的过渡效果。HTML本身不直接支持图像蒙版,但结合CSS可以轻松实现渐变蒙版效果。
使用CSS伪元素实现渐变蒙版
通过为图片容器添加伪元素(如::before或::after),可以在图片上叠加一个渐变层,从而实现蒙版效果。
示例代码:
@@##@@
.image-container {
position: relative;
display: inline-block;
}
.image-container img {
display: block;
width: 100%;
height: auto;
}
.image-container::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(to bottom, rgba(0,0,0,0), rgba(0,0,0,0.7));
pointer-events: none; / 确保不影响图片交互 /
}
使用background-image与渐变叠加
如果图片作为背景图使用,可以直接在background属性中组合图片和渐变。
立即学习“前端免费学习笔记(深入)”;
- 将渐变写在图片前面,实现“蒙版”效果
- 适合全屏背景或卡片设计
示例代码:
.bg-image {
width: 100%;
height: 400px;
background:
linear-gradient(to bottom, rgba(0,0,0,0), rgba(0,0,0,0.6)),
url('example.jpg');
background-size: cover;
background-position: center;
}使用mask-image实现高级渐变遮罩
CSS的mask-image属性可创建真正意义上的图像蒙版,支持从黑到白的透明度控制。
- 白色区域完全显示,黑色区域隐藏
- 渐变可控制显示范围
- 现代浏览器支持良好
示例代码:
.masked-img {
mask-image: linear-gradient(to right, transparent, black 20%, white 80%);
-webkit-mask-image: linear-gradient(to right, transparent, black 20%, white 80%);
}基本上就这些方法。根据实际需求选择合适的方式:伪元素适合简单叠加,background适合背景图,mask-image适合精细控制透明区域。注意兼容性,特别是mask-image在部分旧浏览器中需要-webkit-前缀。











