Tailwind CSS - 反转
Tailwind CSS: Invert(反转)
Section titled “Tailwind CSS: Invert(反转)”Tailwind CSS 中的 invert 实用工具类应用一个 CSS 滤镜,它会反转元素的颜色。这是一个创建视觉效果的强大工具,特别适用于主题化,例如为徽标或图标创建深色模式版本。
Invert 类
Section titled “Invert 类”invert 功能非常直接,主要有两个类。
| 类名 | CSS 属性 |
|---|---|
invert | filter: invert(1); |
invert-0 | filter: invert(0); |
invert:对元素应用完全 100% 的颜色反转。黑色变为白色,白色变为黑色,蓝色变为黄色等。invert-0:应用 0% 的反转,实际上是移除滤镜或确保元素处于正常状态。这对于在特定状态(例如hover:invert-0)下重置invert滤镜很有用。
实用示例:深色模式主题化
Section titled “实用示例:深色模式主题化”invert 最强大的用例之一是使单色资产(如黑色徽标)适应深色主题,而无需创建单独的白色版本资产。通过使用 dark: 变体,我们可以在深色模式激活时才应用 invert 滤镜。
示例:为深色模式反转徽标
Section titled “示例:为深色模式反转徽标”此示例模拟了浅色和深色主题。徽标默认为黑色,但当父容器具有 dark 类时,dark:invert 类会将其翻转为白色。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Invert for Dark Mode</title> <script src="https://cdn.tailwindcss.com"></script> <script> // 要使用 'dark:' 变体,我们需要告诉 Tailwind 如何切换它。 // 此配置允许基于 html 元素上的 'dark' 类进行切换。 tailwind.config = { darkMode: 'class', } </script></head><body class="bg-gray-100 dark:bg-gray-900 transition-colors duration-500">
<div class="p-8 text-center"> <button onclick="document.documentElement.classList.toggle('dark')" class="px-4 py-2 bg-blue-500 text-white rounded mb-8">Toggle Dark Mode</button> </div>
<main class="max-w-md mx-auto bg-white dark:bg-slate-800 p-8 rounded-xl shadow-lg"> <h2 class="text-xl font-bold text-gray-900 dark:text-white mb-4">Company Card</h2> <div class="flex items-center space-x-4"> <!-- 徽标默认为黑色,但在深色模式下变为白色 --> <img src="https://raw.githubusercontent.com/tailwindlabs/tailwindcss/master/src/img/tailwind-mark.svg" alt="Tailwind CSS Logo" class="h-12 w-12 dark:invert" /> <div> <p class="text-lg font-semibold text-gray-900 dark:text-white">Tailwind Labs</p> <p class="text-gray-500 dark:text-gray-400">Modern CSS Framework</p> </div> </div>
<div class="mt-6"> <h3 class="font-medium text-gray-900 dark:text-white">Filter States:</h3> <div class="flex items-center space-x-6 mt-2"> <figure> <img src="https://placehold.co/100x100/3498db/ffffff" alt="Normal image" class="invert-0 rounded-md"/> <figcaption class="text-center text-sm mt-1 dark:text-gray-300">`invert-0`</figcaption> </figure> <figure> <img src="https://placehold.co/100x100/3498db/ffffff" alt="Inverted image" class="invert rounded-md"/> <figcaption class="text-center text-sm mt-1 dark:text-gray-300">`invert`</figcaption> </figure> </div> </div>
</main></body></html>相关实用工具和最佳实践
Section titled “相关实用工具和最佳实践”- 滤镜上下文:
invert是 Tailwind 滤镜 (filter) 实用工具套件的一部分。你可以将其与其他工具(如grayscale、sepia、brightness和saturate)结合使用。 - 应用于组:使用
group-hover在鼠标悬停在父元素上时,将invert滤镜应用于子元素。例如,当用户悬停在整个按钮上时,你可以反转图标的颜色。 - 性能:CSS 滤镜在现代浏览器中是硬件加速的,通常性能良好。但是,对非常大的元素或在快速动画期间应用复杂的滤镜可能会影响性能,因此请务必在目标设备上进行测试。