如何使用 tailwind css `theme` 功能和不透明度修改器

问题描述 投票:0回答:1

有没有办法使用

theme()
语法来声明带有 tailwind 的 css 变量并在之后使用不透明度修饰符?

/*globals.css*/
@layer base {
  :root {
    /*these work fine*/

    --almost-black: 12 12 12;
    --body-color: var(--almost-black);
    --sub-text-color: 107 114 128;

    /*these break when used with opacity modifier syntax*/

    --background-color: theme("colors.gray.50");
    --color-primary: theme("colors.purple.600");
    --color-secondary: theme("colors.purple.300");
  }
}
// my tailwind config
const config: Config = {
 ...
  theme: {
    extend: {
      colors: {
        'body': 'rgb(var(--body-color))',
        'sub-text': 'rgb(var(--sub-text-color))',
        'background': 'rgb(var(--background-color))', // tried this just to sanity test but ofcourse it doesnt work because the output of `theme(colors)` is a hex value 
        'primary': 'var(--color-primary)',
        'secondary': 'var(--color-secondary)',
      }
    },
  },
};

假设我将此类添加到元素中

bg-body/50
Tailwind 会知道我想要什么并输出一些像这样的 css

:is(.dark .dark\:bg-body\/50) {
    background-color: rgb(var(--body-color) / 0.5);
}

但是如果我想用this,似乎没有办法。您会注意到该页面提到了不透明度语法,但它没有谈到将其与变量一起使用,而只是硬编码值。

tailwind-css
1个回答
0
投票

您可以考虑使用 CSS 原生

color-mix()
函数 作为颜色值的一部分。这允许您传递
<alpha-value>
,而无需在运行时“知道”颜色或需要将它们采用组件 RGB/HSL 格式:

tailwind.config = {
  theme: {
    extend: {
      colors: {
        'body': 'rgb(var(--body-color))',
        'sub-text': 'rgb(var(--sub-text-color))',
        'background': 'color-mix(in srgb, var(--background-color) calc(100% * <alpha-value>), transparent)',
        'primary': 'color-mix(in srgb, var(--color-primary) calc(100% * <alpha-value>), transparent)',
        'secondary': 'color-mix(in srgb, var(--color-secondary) calc(100% * <alpha-value>), transparent)',
      }
    },
  },
}
<script src="https://cdn.tailwindcss.com/3.4.4"></script>

<style type="text/tailwindcss">
@layer base {
  :root {
    /*these work fine*/

    --almost-black: 12 12 12;
    --body-color: var(--almost-black);
    --sub-text-color: 107 114 128;

    /*these break when used with opacity modifier syntax*/

    --background-color: theme("colors.gray.50"); 
    --color-primary: theme("colors.purple.600");
    --color-secondary: theme("colors.purple.300");
  }
}
</style>

<div class="bg-primary/75 w-10 h-10"></div>
<div class="bg-primary/50 w-10 h-10"></div>
<div class="bg-primary/25 w-10 h-10"></div>

<div class="bg-secondary/75 w-10 h-10"></div>
<div class="bg-secondary/50 w-10 h-10"></div>
<div class="bg-secondary/25 w-10 h-10"></div>

© www.soinside.com 2019 - 2024. All rights reserved.