Tailwind CSS - 隔离
现代 Tailwind CSS: Isolation(隔离)
Section titled “现代 Tailwind CSS: Isolation(隔离)”isolation 实用工具类控制元素是否应创建新的堆叠上下文(stacking context)。这是一个高级但功能强大的概念,用于管理 z-index 和 mix-blend-mode 效果。
什么是堆叠上下文?
Section titled “什么是堆叠上下文?”堆叠上下文就像一组元素的新的、独立的层叠世界。在堆叠上下文内部,z-index 值仅与同一上下文中的其他元素进行比较。这可以防止一个元素的子元素意外地出现在页面上其他不相关元素的上方或下方。
对元素使用 isolate 是创建新堆叠上下文最直接的方式。
| 类名 | CSS 属性 | 描述 |
|---|---|---|
isolate | isolation: isolate; | 创建一个新的堆叠上下文。它将 z-index 和混合效果限制在该元素内部。 |
isolation-auto | isolation: auto; | 默认值。不创建新的堆叠上下文。 |
实用示例:驯服 mix-blend-mode
Section titled “实用示例:驯服 mix-blend-mode”isolate 的常见用例是限制混合模式。在下面的示例中,我们有一个背景和一些文本。右侧的文本具有 mix-blend-multiply 属性,它会将其与背景混合。
没有 isolate,混合效果由 div 包含。有了 isolate,混合效果被限制在应用它的 div 内部,防止它与页面的主背景混合。
<!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>Isolation Example</title></head><body class="bg-slate-200">
<div class="relative grid grid-cols-1 md:grid-cols-2 gap-8 p-8">
<!-- Card without isolation --> <div class="p-8 bg-amber-300 rounded-xl"> <h3 class="font-bold text-lg mb-2">Without `isolate`</h3> <div class="w-32 h-32 bg-cyan-400 mix-blend-multiply"></div> <p class="-mt-12 ml-6 font-black text-5xl text-white">Text</p> <p class="mt-4 text-sm">The cyan box and 'Text' blend with the amber background because there is no isolated stacking context.</p> </div>
<!-- Card with isolation --> <div class="isolate p-8 bg-amber-300 rounded-xl"> <h3 class="font-bold text-lg mb-2">With `isolate`</h3> <div class="w-32 h-32 bg-cyan-400 mix-blend-multiply"></div> <p class="-mt-12 ml-6 font-black text-5xl text-white">Text</p> <p class="mt-4 text-sm">Here, `isolate` on the parent creates a new stacking context. The blending happens *inside* this context only.</p> </div>
</div>
</body></html>常见陷阱与调试
Section titled “常见陷阱与调试”问题:一个 z-index: -1 的元素消失在主页面背景之后。
解决方案:对其父元素应用 isolate。这会创建一个新的堆叠上下文,因此 z-index: -1 现在会将元素放置在其父元素的堆叠上下文的底部,而不是整个页面的底部。