【问题标题】:Use Color in TailWind CSS在 TailWind CSS 中使用颜色
【发布时间】:2021-09-02 08:12:00
【问题描述】:

如何在 TailWind CSS 中使用颜色?

我正在学习 TailWind CSS。我在 Laravel 中使用 TailWind CSS。

我的tailwind.config.js 如下所示

const { colors } = require('tailwindcss/defaultTheme')

module.exports = {
  purge: [],
  darkMode: false, // or 'media' or 'class'
  theme: {
    colors: {
      cadetblue:'#5f9ea0',
    },
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

我在<head></head> 中声明的 CSS 如下所示。

<style>
 .hello { background-color: theme('colors.cadetblue'); }
</style>

我在 HTML 中使用.hello 类,如下所示。

<div class="hello">Hello</div>

但这不起作用。

【问题讨论】:

    标签: tailwind-css


    【解决方案1】:

    首先,您需要在您的自定义theme 文件中定义colors 对象数组,因为您的tailwind 配置将覆盖默认值。所以请检查您的colors 导入是否与官方文档相同,

    const colors = require('tailwindcss/colors')
    

    解决方案 1

    将您的自定义颜色名称定义为theme.colors

    const colors = require("tailwindcss/colors");
    
    module.exports = {
      purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],
      ...
      theme: {
      ...
        colors: {
          cadetblue: "#5f9ea0",
        },
      ...
    

    解决方案 2

    另外,你可以简单地在你的主css文件中定义它,Official Doc Link

    // in your css file
    
    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
    ...
    # You can add your custom class name into `utilities`
    @layer utilities { 
      .bg-cadetblue {
        background-color: #5f9ea0;
      }
    }
    

    并使用它

    <div class="bg-cadetblue">Hello</div>
    

    ps,请使用 npm run startyarn start 重新启动您的应用程序!

    编码愉快:)

    【讨论】:

    • 感谢@JsWizard 的回复。 // in your css file .bg-cadetblue { background-color: #5f9ea0 } 是 TailWind CSS 吗?我正在学习 TailWind CSS。谢谢。
    • 欢迎阿布,Tailwind 也使用类似的方式来使用 CSS,所有 Tailwind 类也使用 CSS 预制。
    • 感谢@JsWizard。我正在学习 TailWind CSS。我该如何实施您的解决方案?你能描述更多吗?
    • 再次检查我修改后的答案,祝你好运!! :)
    • 检查您的purge 定义,这是推荐设置,purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"], :)
    猜你喜欢
    • 1970-01-01
    • 2021-09-20
    • 2021-11-23
    • 2020-11-10
    • 2021-08-30
    • 2021-12-23
    • 2022-11-27
    • 2023-02-04
    • 2022-11-13
    相关资源
    最近更新 更多