CSS 混合模式
学习mix-blend-mode · 难度:高级 · +15XP
CSS 混合模式 mix-blend-mode
mix-blend-mode 控制元素内容与其下方背景的混合方式,类似于 Photoshop 中的图层混合模式。配合 background-blend-mode,可以为网页创造独特的视觉效果。
所有混合模式
| 模式 | 效果描述 |
|---|---|
normal | 默认,不混合 |
multiply | 正片叠底 — 颜色相乘,结果更暗 |
screen | 滤色 — 颜色反转相乘再反转,结果更亮 |
overlay | 叠加 — 结合 multiply 和 screen |
darken | 变暗 — 取每个通道较暗值 |
lighten | 变亮 — 取每个通道较亮值 |
color-dodge | 颜色减淡 — 亮度大幅提升 |
color-burn | 颜色加深 — 亮度大幅降低 |
difference | 差值 — 反转底层颜色 |
exclusion | 排除 — 类似 difference 但对比度更低 |
基本语法
.blend-element {
mix-blend-mode: multiply;
}
.background-blend {
background: url('texture.jpg'), linear-gradient(red, blue);
background-blend-mode: overlay;
}
mix-blend-mode vs background-blend-mode
| 属性 | 混合对象 |
|---|---|
mix-blend-mode | 元素内容 与 其下方所有元素的背景 |
background-blend-mode | 同一个元素的多个背景图像之间 |
经典应用场景
文字与图片混合
.hero {
position: relative;
background: url('hero.jpg') center/cover;
height: 80vh;
}
.hero h1 {
color: white;
mix-blend-mode: difference;
/* 文字在亮区域变暗,暗区域变亮,始终可读 */
}
纹理叠加
.textured {
background:
url('grain-texture.jpg'),
linear-gradient(135deg, #667eea, #764ba2);
background-blend-mode: overlay;
/* 纹理叠在渐变上,创造丰富质感 */
}
品牌色图片处理
.brand-image {
position: relative;
}
.brand-image img {
display: block;
width: 100%;
}
.brand-image::after {
content: '';
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
background: #2196F3;
mix-blend-mode: color;
opacity: 0.6;
}
isolation — 隔离混合
使用 isolation: isolate 可以创建一个新的层叠上下文,防止内部元素的混合模式影响外部:
.container {
isolation: isolate; /* 隔离内部混合 */
}
.container .blend {
mix-blend-mode: multiply;
/* 混合仅发生在 .container 内部 */
}
注意事项
- 混合模式不影响布局,仅影响视觉呈现
mix-blend-mode在部分场景下会影响文字可读性difference和screen需注意对比度- 在暗色/亮色模式切换时,混合效果可能导致不可预期的结果
- 性能良好,使用 GPU 加速
混合模式为网页设计打开了创意的大门,让你可以在浏览器中实现以前只能用图像处理软件才能完成的效果。