Skip to content

Tailwind CSS - 背景混合模式

Tailwind 的 background-blend-mode 工具类允许您定义元素的多个背景层(如图像和颜色)应如何混合在一起。这将 Photoshop 等图形设计工具的功能直接带入您的 CSS,从而实现丰富的、分层的视觉效果。

以下是所有可用的 bg-blend-* 工具类的完整列表。

类名CSS 属性
bg-blend-normalbackground-blend-mode: normal;
bg-blend-multiplybackground-blend-mode: multiply;
bg-blend-screenbackground-blend-mode: screen;
bg-blend-overlaybackground-blend-mode: overlay;
bg-blend-darkenbackground-blend-mode: darken;
bg-blend-lightenbackground-blend-mode: lighten;
bg-blend-color-dodgebackground-blend-mode: color-dodge;
bg-blend-color-burnbackground-blend-mode: color-burn;
bg-blend-hard-lightbackground-blend-mode: hard-light;
bg-blend-soft-lightbackground-blend-mode: soft-light;
bg-blend-differencebackground-blend-mode: difference;
bg-blend-exclusionbackground-blend-mode: exclusion;
bg-blend-huebackground-blend-mode: hue;
bg-blend-saturationbackground-blend-mode: saturation;
bg-blend-colorbackground-blend-mode: color;
bg-blend-luminositybackground-blend-mode: luminosity;

要使用混合模式,一个元素必须至少有两个背景层。这通常是一个背景图像和一个背景颜色或渐变。混合模式定义了顶层(例如颜色)如何与其下方的层(例如图像)进行交互。

此示例展示了如何通过将背景图像与渐变混合来创建流行的“双色调(duotone)”图像效果。我们还会利用 :hover 伪类改变混合模式,以实现动态效果。

注意: 要使用自定义背景图像,您必须在 tailwind.config.js 文件中定义它们。为了简化本示例,我们将使用内联样式,但推荐的做法是使用您的配置文件。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Background Blend Mode Example</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-200 p-8 flex items-center justify-center min-h-screen">
<div
class="w-96 h-64 rounded-xl shadow-lg bg-cover bg-center
bg-gradient-to-br from-cyan-500 to-fuchsia-500
bg-blend-multiply hover:bg-blend-screen
transition-all duration-500 flex items-center justify-center"
style="background-image: url('https://images.unsplash.com/photo-1554629947-334ff61d85dc?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80')">
<h2 class="text-white text-3xl font-bold mix-blend-overlay">Hover Me</h2>
</div>
</body>
</html>
  • 图像滤镜: 使用 bg-blend-multiply 或 bg-blend-screen 结合纯色背景,快速为图像应用颜色滤镜。
  • 纹理背景: 将微妙的纹理图像与纯色混合,为您的布局增加深度。
  • 交互效果: 使用 hover: 和 focus: 变体(variants)来改变混合模式,以实现交互反馈。
  • mix-blend-mode: 要将整个元素与其背后的内容混合,请探索 mix-blend-* 工具类,这些类应用于元素本身,而不仅仅是其背景。

处理背景图像的推荐方法是在 tailwind.config.js 文件中进行配置。这使得您可以为它们指定语义化的名称并轻松复用。

tailwind.config.js
module.exports = {
theme: {
extend: {
backgroundImage: {
'hero-pattern': "url('/img/hero-pattern.svg')",
'footer-texture': "url('/img/footer-texture.png')",
}
}
}
}
// 在 HTML 中的用法
// <div class="bg-hero-pattern">...</div>