UnoCSS 是一个高性能且极具灵活性的即时原子化 CSS 引擎。以下是 UnoCSS 的详细解析:
-
核心特性:
- 完全可定制:所有规则都可以定制。
- 属性模式:支持属性模式,可以直接在 HTML 属性中使用。
- 纯 CSS 图标:支持纯 CSS 图标解决方案。
- 变体组:支持变体组,可以更方便地组合多个变体。
- CSS 作用域:支持 CSS 作用域,可以避免样式冲突。
- 代码分割:支持按需生成 CSS,减小文件体积。
-
基本用法:
在 HTML 中直接使用预定义的原子类:
<div class="text-center font-bold text-2xl color-blue-500"> Hello UnoCSS </div> -
自定义规则:
在配置文件中自定义规则:
// uno.config.ts import { defineConfig } from 'unocss' export default defineConfig({ rules: [ ['custom-rule', { color: 'red' }] ] }) -
预设:
UnoCSS 提供了多种预设,如默认预设、Wind 预设(类似 Tailwind)等:
import { defineConfig, presetUno, presetAttributify, presetIcons } from 'unocss' export default defineConfig({ presets: [ presetUno(), presetAttributify(), presetIcons() ] }) -
主题配置:
可以自定义主题,如颜色、字体大小等:
export default defineConfig({ theme: { colors: { primary: '#3490dc', secondary: '#ffed4a' }, fontSizes: { sm: '0.875rem', base: '1rem', lg: '1.125rem' } } }) -
快捷方式:
定义常用的类组合:
export default defineConfig({ shortcuts: { 'btn': 'py-2 px-4 font-semibold rounded-lg shadow-md', 'btn-green': 'text-white bg-green-500 hover:bg-green-700' } }) -
变体:
定义条件样式:
export default defineConfig({ variants: [ (matcher) => { if (!matcher.startsWith('hover:')) return matcher return { // 处理 hover 变体 matcher: matcher.slice(6), selector: s => `${s}:hover` } } ] }) -
属性模式:
直接在 HTML 属性中使用样式:
<button bg="blue-400 hover:blue-500 dark:blue-500 dark:hover:blue-600" text="sm white" font="mono light" p="y-2 x-4" border="2 rounded blue-200" > Button </button> -
图标支持:
使用纯 CSS 图标:
<div class="i-carbon-airplay text-3xl" /> -
与构建工具集成:
UnoCSS 可以与 Vite、Webpack、Rollup 等构建工具集成,通过插件形式使用。
UnoCSS 的灵活性和高性能使其成为现代 Web 开发中的强大工具。它允许开发者快速构建自定义设计系统,同时保持了极高的性能和小的文件体积。通过其丰富的配置选项,开发者可以根据项目需求精确控制生成的 CSS。