Skip to content

Tailwind CSS - 背景不透明度

使用背景滤镜创建磨砂玻璃效果

Section titled “使用背景滤镜创建磨砂玻璃效果”

Tailwind 的背景滤镜(backdrop-filter)工具类允许你对元素后面的区域应用模糊、亮度、不透明度等图形效果。backdrop-opacity-* 类专门控制给定元素后面可见内容的透明度。

使用这些工具类来控制背景的不透明度。此效果要求元素具有半透明背景。

类名CSS 属性
backdrop-opacity-0—tw-backdrop-opacity: 0;
backdrop-opacity-5—tw-backdrop-opacity: 0.05;
backdrop-opacity-10—tw-backdrop-opacity: 0.1;
backdrop-opacity-25—tw-backdrop-opacity: 0.25;
backdrop-opacity-50—tw-backdrop-opacity: 0.5;
backdrop-opacity-75—tw-backdrop-opacity: 0.75;
backdrop-opacity-100—tw-backdrop-opacity: 1;

注意: Tailwind 使用 CSS 自定义属性(--tw-backdrop-opacity)将多个背景滤镜(如 blur 模糊、saturate 饱和度等)组合成一个 backdrop-filter 声明。

  • 核心要求:要使任何 backdrop-* 工具类可见,元素必须具有一定程度的透明度。这通常通过设置带有 alpha 通道(透明度通道)的背景颜色来实现,例如 bg-black/50 或 bg-white/70(/ 语法是 Tailwind 现代的不透明度简写)。
  • 常见用例:最流行的应用是创建“磨砂玻璃” UI 元素,例如模态对话框(modal dialogs)、导航栏或浮动在其他内容之上的侧边栏。

实际应用:使用背景滤镜构建模态框

Section titled “实际应用:使用背景滤镜构建模态框”

此示例展示了一个按钮,点击后会显示一个模态对话框。模态框后面的叠加层使用了 backdrop-blur 和半透明背景,以创建现代的磨砂玻璃效果。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.tailwindcss.com"></script>
<title>Backdrop Filter Modal</title>
</head>
<body class="bg-slate-200">
<!-- Background Content -->
<div class="relative p-8">
<img alt="Abstract background" class="absolute inset-0 w-full h-full object-cover" src="https://placehold.co/1200x800/d1d5db/374151?text=Background">
<div class="relative max-w-xl mx-auto bg-white/75 p-8 rounded-lg shadow-xl">
<h1 class="text-3xl font-bold text-slate-900">Main Content</h1>
<p class="text-slate-700 mt-4">This is the content on the page, which will be visible behind the modal's backdrop. Click the button to see the effect.</p>
<button onclick="document.getElementById('modal').classList.remove('hidden')" class="mt-6 bg-indigo-600 text-white font-bold py-2 px-4 rounded-lg hover:bg-indigo-700 transition-colors">Open Modal</button>
</div>
</div>
<!-- Modal with Backdrop -->
<div id="modal" class="hidden fixed inset-0 z-10 flex items-center justify-center">
<!-- Backdrop Overlay: semi-transparent background + backdrop blur -->
<div class="absolute inset-0 bg-black/30 backdrop-blur-sm"></div>
<!-- Modal Content -->
<div class="relative bg-white w-full max-w-md p-6 rounded-xl shadow-2xl m-4">
<h2 class="text-xl font-bold text-slate-800">Modal Dialog</h2>
<p class="text-slate-600 mt-2">Notice the 'frosted glass' effect on the background content behind this modal.</p>
<button onclick="document.getElementById('modal').classList.add('hidden')" class="mt-6 bg-slate-200 text-slate-800 font-bold py-2 px-4 rounded-lg hover:bg-slate-300 transition-colors">Close</button>
</div>
</div>
</body>
</html>

backdrop-filter 属性在所有现代浏览器(Chrome、Firefox、Safari、Edge)中都得到了很好的支持。然而,它在 Internet Explorer 等旧版浏览器中不受支持。由于它纯粹是一种美学效果,因此非常适合作为渐进增强(progressive enhancement)的候选特性。现代浏览器的用户将获得增强的体验,而旧版浏览器的用户将只看到一个没有模糊效果的半透明叠加层,这也是一个完全可以接受的兼容性方案。