Skip to content

什么是 UnoCSS?

🌐 What is UnoCSS?

UnoCSS 是即时原子 CSS 引擎,旨在灵活且可扩展。核心不带偏见,所有 CSS 工具类都通过预设提供。

🌐 UnoCSS is the instant atomic CSS engine, that is designed to be flexible and extensible. The core is un-opinionated and all the CSS utilities are provided via presets.

例如,你可以通过在本地配置文件中提供规则来定义自定义 CSS 工具类。

🌐 For example, you could define your custom CSS utilities, by providing rules in your local config file.

uno.config.ts
ts
import { defineConfig } from 'unocss'

export default defineConfig({
  rules: [
    ['m-1', { margin: '1px' }],
  ],
})

这将向你的项目添加一个新的 CSS 工具类 m-1。由于 UnoCSS 是按需加载的,它在你未在代码中使用时不会有任何作用。假设我们有一个像这样的组件:

🌐 This will add a new CSS utility m-1 to your project. Since UnoCSS is on-demand, it won't do anything until you use it in your codebase. So say we have a component like this:

html
<div class="m-1">Hello</div>

m-1 将被检测到,并将生成以下 CSS:

css
.m-1 { margin: 1px; }

为了让它更灵活,你可以通过将规则的第一个参数(我们称之为匹配器)改为 RegExp,并将规则主体改为一个函数,例如:

🌐 To make it more flexible, you can make your rule dynamic by changing the first argument on the rule (we call it matcher) to a RegExp, and the body to a function, for example:

uno.config.ts
diff
export default defineConfig({
  rules: [
-    ['m-1', { margin: '1px' }],
+    [/^m-([\.\d]+)$/, ([_, num]) => ({ margin: `${num}px` })],
  ],
})

通过这样做,现在你可以拥有任意的边距工具类,比如 m-1m-100m-52.43。同样地,UnoCSS 仅在你使用它们时才会生成这些类。

🌐 By doing this, now you can have arbitrary margin utilities, like m-1, m-100 or m-52.43. And again, UnoCSS only generates them whenever you use them.

html
<div class="m-1">Hello</div>
<div class="m-7.5">World</div>
css
.m-1 { margin: 1px; }
.m-7.5 { margin: 7.5px; }

预设

🌐 Presets

一旦你制定了几条规则,你可以将它们提取为预设,并与他人分享。例如,你可以为公司的设计系统创建一个预设,并与团队分享。

🌐 Once you made a few rules, you can extract them into a preset, and share it with others. For example, you can create a preset for your company's design system, and share it with your team.

my-preset.ts
ts
import { Preset } from 'unocss'

export const myPreset: Preset = {
  name: 'my-preset',
  rules: [
    [/^m-([.\d]+)$/, ([_, num]) => ({ margin: `${num}px` })],
    [/^p-([.\d]+)$/, ([_, num]) => ({ padding: `${num}px` })],
  ],
  variants: [/* ... */],
  shortcuts: [/* ... */],
  // ...
}
uno.config.ts
ts
import { defineConfig } from 'unocss'
import { myPreset } from './my-preset'

export default defineConfig({
  presets: [
    myPreset, // your own preset
  ],
})

同样地,我们提供了一些官方预设供你立即使用,你还可以找到许多有趣的社区预设

🌐 So similarly, we provided a few official presets for you to start using right away, and you can also find many interesting community presets.

练习

🌐 Play

你可以在浏览器中尝试 UnoCSS,在 Playground中。或者在 互动文档中查看默认预设的工具。

集成

🌐 Integrations

UnoCSS 集成了各种框架/工具:

🌐 UnoCSS comes with integrations for various frameworks / tools:

示例

🌐 Examples

所有示例的源代码可以在 /examples 目录中找到。

🌐 Source code for all the examples can be found in the /examples directory.