Skip to content

主题

UnoCSS 还支持你可能在 Tailwind CSS 或 Windi CSS 中熟悉的主题系统。在用户层面,你可以在配置中指定 theme 属性,它将深度合并到默认主题中。

使用方法

ts
theme: {
  // ...
  colors: {
    veryCool: '#0000ff', // class="text-very-cool"
    brand: {
      primary: 'hsl(var(--hue, 217) 78% 51%)', //class="bg-brand-primary"
      DEFAULT: '#942192' //class="bg-brand"
    },
  },
}

提示

在解析过程中,theme 将始终存在于 context 中。

rules 中使用

在规则中使用主题:

ts
rules: [
  [/^text-(.*)$/, ([, c], { theme }) => {
    if (theme.colors[c])
      return { color: theme.colors[c] }
  }],
]

variants 中使用

要在变体中使用主题:

ts
variants: [
  {
    name: 'variant-name',
    match(matcher, { theme }) {
      // ...
    },
  },
]

shortcuts 中使用

要在动态快捷方式中使用主题:

ts
shortcuts: [
  [/^badge-(.*)$/, ([, c], { theme }) => {
    if (Object.keys(theme.colors).includes(c))
      return `bg-${c}4:10 text-${c}5 rounded`
  }],
]

断点

警告

当提供自定义的 breakpoints 对象时,默认值将被覆盖,而不是合并。

通过以下示例,你将只能使用 sm:md: 断点变体:

ts
theme: {
  // ...
  breakpoints: {
    sm: '320px',
    md: '640px',
  },
}

如果你想继承 原始 主题的断点,可以使用 extendTheme

ts
extendTheme: (theme) => {
  return {
    ...theme,
    breakpoints: {
      ...theme.breakpoints,
      sm: '320px',
      md: '640px',
    },
  }
}

信息

verticalBreakpointsbreakpoints 类似,但它是用于垂直布局的。

此外,我们将按大小(相同单位)对屏幕断点进行排序。对于不同单位的屏幕断点,为避免出错,请在配置中使用统一的单位。

ts
theme: {
  // ...
  breakpoints: {
    sm: '320px',
    // Because uno does not support comparison sorting of different unit sizes, please convert to the same unit.
    // md: '40rem',
    md: `${40 * 16}px`,
    lg: '960px',
  },
}

扩展主题

ExtendTheme 允许你编辑 深度合并后的主题 以获取完整的主题对象。

自定义函数可以改变主题对象。

ts
extendTheme: (theme) => {
  theme.colors.veryCool = '#0000ff' // class="text-very-cool"
  theme.colors.brand = {
    primary: 'hsl(var(--hue, 217) 78% 51%)', // class="bg-brand-primary"
  }
}

也可以返回一个新的主题对象来完全替换原始对象。

ts
extendTheme: (theme) => {
  return {
    ...theme,
    colors: {
      ...theme.colors,
      veryCool: '#0000ff', // class="text-very-cool"
      brand: {
        primary: 'hsl(var(--hue, 217) 78% 51%)', // class="bg-brand-primary"
      },
    },
  }
}