如何在悬停时在 Tailwind 中实现平滑的背景颜色变化?

dop*_*llo 3 css-transitions tailwind-css

我正在尝试更改悬停时元素的背景颜色。通常情况下,我会使用

className='bg-white hover:bg-black'

这会立即改变颜色,但我想添加 150 毫秒从颜色 A 到颜色 B 的过渡时间。

阅读文档后,我尝试了类似的方法

className='transition-colors ease-linear duration-300 bg-white hover:bg-gradient-to-r from-[#04348B] to-[#0854e2d0]'

这没有任何作用。我混合并匹配了不同的状态等,但找不到解决方案。有人知道这个问题的快速解决方法吗?

我试过:

className='transition-colors ease-linear duration-300 bg-white hover:bg-gradient-to-r from-[#04348B] to-[#0854e2d0]'

className='transition-[background-color] duration-300 bg-white hover:bg-gradient-to-r from-[#04348B] to-[#0854e2d0]'

小智 7

要在悬停时在 Tailwind 中创建平滑的背景颜色变化,您可以使用以下语法:

className='bg-white transition-colors duration-300 ease-in-out hover:bg-black'
Run Code Online (Sandbox Code Playgroud)

解释:

  • bg-white将元素的初始背景颜色设置为白色。
  • transition-colors启用颜色变化的过渡效果。
  • duration-300将过渡效果的持续时间设置为 300 毫秒。
  • ease-in-out将过渡计时功能设置为ease-in-out,可提供平滑的过渡效果。
  • hover:bg-black悬停时将元素的背景颜色设置为黑色。

您应该避免在一个元素中使用两个类属性,因为这可能会导致冲突并使代码难以阅读。相反,您可以将这些类链接在一起,并在它们之间留一个空格。