【问题标题】:How to target elements with a specific data attribute with Tailwind CSS?如何使用 Tailwind CSS 定位具有特定数据属性的元素?
【发布时间】:2022-07-30 10:35:13
【问题描述】:

我有几个消息框,每个框都有一个数据作者属性。

如果我想在 CSS 中为这些消息框应用样式,我可以这样做:

[data-author="Ben"] {
  background-color: blue;
}

但我不确定如何使用 Tailwind CSS 执行此操作,或者是否可能。有什么想法吗?

谢谢

【问题讨论】:

    标签: tailwind-css


    【解决方案1】:

    您可以使用上面使用的语法。对于实现问题,您可以使用@apply 指令,该指令可以直接从tailwind 调用实用程序类

    此外,您还可以通过使用任意值来应用顺风颜色之外的颜色

    [data-author="Ben"] {
      @apply bg-[#bada55];
    }
    

    您可以在本文中了解有关任意值的更多信息:

    https://tailwindcss.com/docs/adding-custom-styles#using-arbitrary-values

    【讨论】:

      【解决方案2】:

      这对于顺风是不可能的,你只能通过给元素类来定位元素。但是,您仍然可以编写自定义 CSS 并使用 tailwind 的 @apply 添加样式:

      [data-author="Ben"] {
        @apply bg-blue-500;
      }
      

      【讨论】:

        【解决方案3】:

        您可以通过添加变体来做到这一点。在你的tailwind.config.js:

        在页面顶部添加const plugin = require('tailwindcss/plugin')

        然后在你的导出中添加:

          plugins: [
            plugin(({ addVariant }) => {
              addVariant('ben', '&[data-author="Ben"]')
            }),
          ]
        

        您所要做的就是按照您的意愿使用它:ben:bg-blue-500

        您需要为每个作者创建一个新的,或者想出一个按颜色分组的约定。

        【讨论】:

          猜你喜欢
          • 2013-10-16
          • 2022-11-02
          • 2019-08-23
          • 2014-02-01
          • 2023-03-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-06-13
          相关资源
          最近更新 更多