Skip to content

规则

¥Rules

规则定义工具类和生成的 CSS。UnoCSS 有许多内置规则,但也允许轻松添加自定义规则。

¥Rules define utility classes and the resulting CSS. UnoCSS has many built-in rules but also allows for easily adding custom rules.

静态规则

¥Static rules

以此为例:

¥With this example:

ts
rules: [
  ['m-1', { margin: '0.25rem' }],
]

每当在用户的代码库中检测到 m-1 时,就会生成以下 CSS:

¥The following CSS will be generated whenever m-1 is detected in users' codebase:

css
.m-1 { margin: 0.25rem; }

注意:正文语法遵循 CSS 属性语法,例如。 font-weight 而不是 fontWeight。如果属性名称中有连字符 -,则应将其括起来。

¥Note: The body syntax follows CSS property syntax, eg. font-weight instead of fontWeight. If there is a hyphen - in the property name it should be quoted.

ts
rules: [
  ['font-bold', { 'font-weight': 700 }],
]

动态规则

¥Dynamic rules

为了使其更智能,请将匹配器更改为 RegExp,将主体更改为函数:

¥To make it smarter, change the matcher to a RegExp and the body to a function:

ts
rules: [
  [/^m-(\d+)$/, ([, d]) => ({ margin: `${d / 4}rem` })],
  [/^p-(\d+)$/, match => ({ padding: `${match[1] / 4}rem` })],
]

body 函数的第一个参数是 RegExp 匹配结果,可以对其进行解构以获得匹配的组。

¥The first argument of the body function is the RegExp match result that can be destructured to get the matched groups.

例如,使用以下用法:

¥For example, with the following usage:

html
<div class="m-100">
  <button class="m-3">
    <icon class="p-5" />
    My Button
  </button>
</div>

将会生成相应的 CSS:

¥the corresponding CSS will be generated:

css
.m-100 { margin: 25rem; }
.m-3 { margin: 0.75rem; }
.p-5 { padding: 1.25rem; }

恭喜!现在你已经拥有了自己强大的原子 CSS 工具。享受!

¥Congratulations! Now you've got your own powerful atomic CSS utilities. Enjoy!

CSS 规则回退

¥CSS Rules Fallback

如果你希望利用 CSS 规则回退来使用新的 CSS 功能,同时还能够回退以支持旧浏览器,你可以选择返回一个 2D 数组作为具有相同键的规则的 CSS 表示。例如:

¥In cases you might want to leverage CSS rules fallback to use new CSS features while also able to fallback to support old browsers, you can optionally return a 2D-array as the CSS representation for rules with the same keys. For example:

ts
rules: [
  [/^h-(\d+)dvh$/, ([_, d]) => {
    return [
      ['height', `${d}vh`],
      ['height', `${d}dvh`],
    ]
  }],
]

这将使 h-100dvh 生成:

¥Which will make h-100dvh generates:

css
.h-100dvh { height: 100vh; height: 100dvh; }

排序

¥Ordering

UnoCSS 尊重你在生成的 CSS 中定义的规则的顺序。后者具有更高的优先级。

¥UnoCSS respects the order of the rules you defined in the generated CSS. Latter ones come with higher priority.

当使用动态规则时,它可能会匹配多个标记。默认情况下,在单个动态规则下匹配的输出将在组内按字母顺序排序。

¥When using dynamic rules, it may match multiple tokens. By default, the output of those matched under a single dynamic rule will be sorted alphabetically within the group.

规则合并

¥Rules merging

默认情况下,UnoCSS 会将 CSS 规则与同一正文合并,以最小化 CSS 大小。

¥By default, UnoCSS will merge CSS rules with the same body to minimize the CSS size.

例如,<div class="m-2 hover:m2"> 将生成:

¥For example, <div class="m-2 hover:m2"> will generate:

css
.hover\:m2:hover, .m-2 { margin: 0.5rem; }

而不是两个单独的规则:

¥Instead of two separate rules:

css
.hover\:m2:hover { margin: 0.5rem; }
.m-2 { margin: 0.5rem; }

特殊符号

¥Special symbols

自 v0.61 以来,UnoCSS 支持特殊符号来为生成的 CSS 定义额外的元信息。你可以从动态规则匹配器函数的第二个参数访问符号。

¥Since v0.61, UnoCSS supports special symbols to define additional meta information for your generated CSS. You can access symbols from the second argument of the dynamic rule matcher function.

例如:

¥For example:

ts
rules: [
  [/^grid$/, ([, d], { symbols }) => {
    return {
      [symbols.parent]: '@supports (display: grid)',
      display: 'grid',
    }
  }],
]

将生成:

¥Will generate:

css
@supports (display: grid) {
  .grid {
    display: grid;
  }
}

可用符号

¥Available symbols

  • symbols.parent:生成的 CSS 规则的父封装器(例如 @supports@media 等)

    ¥symbols.parent: The parent wrapper of the generated CSS rule (eg. @supports, @media, etc.)

  • symbols.selector:一个函数,用于修改生成的 CSS 规则的选择器(见下面的示例)

    ¥symbols.selector: A function to modify the selector of the generated CSS rule (see the example below)

  • symbols.layer:设置生成的 CSS 规则的 UnoCSS 层的字符串/函数/正则表达式匹配

    ¥symbols.layer: A string/function/regex match that sets the UnoCSS layer of the generated CSS rule

  • symbols.variants:应用于当前 CSS 对象的变体处理程序数组

    ¥symbols.variants: An array of variant handler that are applied to the current CSS object

  • symbols.shortcutsNoMerge:一个布尔值,用于禁用快捷方式中当前规则的合并

    ¥symbols.shortcutsNoMerge: A boolean to disable the merging of the current rule in shortcuts

多选择器规则

¥Multi-selector rules

自 v0.61 以来,UnoCSS 通过 JavaScript 生成器函数 支持多选择器。

¥Since v0.61, UnoCSS supports multi-selector via JavaScript Generator functions.

例如:

¥For example:

ts
rules: [
  [/^button-(.*)$/, function* ([, color], { symbols }) {
    yield {
      background: color
    }
    yield {
      [symbols.selector]: selector => `${selector}:hover`,
      // https://web.nodejs.cn/en-US/docs/Web/CSS/color_value/color-mix
      background: `color-mix(in srgb, ${color} 90%, black)`
    }
  }],
]

将生成多个 CSS 规则:

¥Will generate multiple CSS rules:

css
.button-red {
  background: red;
}
.button-red:hover {
  background: color-mix(in srgb, red 90%, black);
}

完全受控的规则

¥Fully controlled rules

提示

这是一项高级功能,在大多数情况下不需要它。

¥This is an advanced feature, in most situtations it won't be needed.

当你确实需要一些 动态规则变体 组合未涵盖的高级规则时,UnoCSS 还提供了一种方法来让你完全控制生成 CSS。

¥When you really need some advanced rules that aren't covered by the combination of Dynamic Rules and Variants, UnoCSS also provides a way to give you full control to generate the CSS.

它允许你从动态规则的主体函数返回一个字符串,该字符串将直接传递给生成的 CSS(这也意味着你需要处理 CSS 转义、变体应用、CSS 构造等事情)。

¥It allows you to return a string from the dynamic rule's body function which will be directly passed to the generated CSS (this also means you need to take care of things like CSS escaping, variant applying, CSS constructing, and so on).

uno.config.ts
ts
import { defineConfig, toEscapedSelector as e } from 'unocss'

export default defineConfig({
  rules: [
    [/^custom-(.+)$/, ([, name], { rawSelector, currentSelector, variantHandlers, theme }) => {
      // discard mismatched rules
      if (name.includes('something'))
        return

      // if you want, you can disable the variants for this rule
      if (variantHandlers.length)
        return
      const selector = e(rawSelector)
      // return a string instead of an object
      return `
${selector} {
  font-size: ${theme.fontSize.sm};
}
/* you can have multiple rules */
${selector}::after {
  content: 'after';
}
.foo > ${selector} {
  color: red;
}
/* or media queries */
@media (min-width: ${theme.breakpoints.sm}) {
  ${selector} {
    font-size: ${theme.fontSize.sm};
  }
}
`
    }],
  ],
})