# 10. UnoCSS 使用指南
URL: /%E6%96%87%E6%A1%A3/04.%E5%BC%80%E5%8F%91%E6%96%87%E6%A1%A3/01.%20%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91/01.%20%E5%9F%BA%E7%A1%80%E8%A7%84%E8%8C%83/10.%20UnoCSS%20%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97

UnoCSS 原子化 CSS 框架完整使用指南


# UnoCSS 使用指南

> [!info] UnoCSS 是一个即时的原子化 CSS 引擎，比 Tailwind CSS/WindiCSS 更快、更轻量。

## 项目配置

### 配置文件

项目根目录 `uno.config.ts`：

```typescript
import { defineConfig, presetUno } from "unocss";
import presetIcons from "@unocss/preset-icons";
import { FileSystemIconLoader } from "@iconify/utils/lib/loader/node-loaders";
import fs from "fs";

const iconsDir = "./src/assets/icons";

const generateSafeList = () => {
  try {
    return fs
      .readdirSync(iconsDir)
      .filter((file) => file.endsWith(".svg"))
      .map((file) => `i-svg:${file.replace(".svg", "")}`);
  } catch (error) {
    console.error("无法读取图标目录:", error);
    return [];
  }
};

export default defineConfig({
  presets: [
    presetUno(),
    presetIcons({
      extraProperties: {
        width: "1em",
        height: "1em",
        display: "inline-block",
      },
      collections: {
        svg: FileSystemIconLoader(iconsDir, (svg) => {
          return svg.includes('fill="')
            ? svg
            : svg.replace(/^<svg /, '<svg fill="currentColor" ');
        }),
      },
    }),
  ],
  safelist: generateSafeList(),
});
```

## 与 Ant Design Vue 共存

UnoCSS 与 Ant Design Vue 可以完美共存：

```vue
<template>
  <!-- Ant Design Vue 组件 -->
  <a-button class="!flex items-center gap-2">
    <span class="i-mdi:home" />
    按钮
  </a-button>

  <!-- 自定义组件使用 UnoCSS -->
  <div class="flex items-center justify-between p-4 bg-white rounded-lg shadow">
    <span class="text-lg font-bold">标题</span>
  </div>
</template>

<style scoped>
/* 可以继续使用 Less */
.custom-style {
  color: @primary-color;
}
</style>
```

## 常用工具类速查

### 布局

| 类名 | 说明 | 类名 | 说明 |
|------|------|------|------|
| `flex` | 弹性布局 | `grid` | 网格布局 |
| `block` | 块级 | `inline-block` | 行内块 |
| `hidden` | 隐藏 | `visible` | 显示 |

### Flexbox

| 类名 | 说明 | 类名 | 说明 |
|------|------|------|------|
| `flex-row` | 水平方向 | `flex-col` | 垂直方向 |
| `items-center` | 垂直居中 | `items-start` | 垂直顶部 |
| `justify-center` | 水平居中 | `justify-between` | 两端对齐 |
| `flex-1` | 占满剩余空间 | `flex-wrap` | 换行 |

### 间距

| 类名 | 说明 | 类名 | 说明 |
|------|------|------|------|
| `p-4` | padding: 1rem | `m-4` | margin: 1rem |
| `px-2` | padding-x: 0.5rem | `py-1` | padding-y: 0.25rem |
| `mt-2` | margin-top: 0.5rem | `mb-4` | margin-bottom: 1rem |

### 尺寸

| 类名 | 说明 | 类名 | 说明 |
|------|------|------|------|
| `w-full` | width: 100% | `h-screen` | height: 100vh |
| `w-1/2` | width: 50% | `h-10` | height: 2.5rem |
| `max-w-md` | max-width: 28rem | `min-h-screen` | min-height: 100vh |

### 文字

| 类名 | 说明 | 类名 | 说明 |
|------|------|------|------|
| `text-sm` | font-size: 0.875rem | `text-lg` | font-size: 1.125rem |
| `font-bold` | font-weight: 700 | `font-normal` | font-weight: 400 |
| `text-center` | text-align: center | `text-left` | text-align: left |
| `truncate` | 文本溢出省略 | `line-clamp-2` | 限制2行 |

### 颜色

| 类名 | 说明 | 类名 | 说明 |
|------|------|------|------|
| `bg-white` | background: white | `bg-blue-500` | background: #3b82f6 |
| `text-black` | color: black | `text-red-500` | color: #ef4444 |
| `border-gray-200` | border-color: #e5e7eb | `divide-y` | 水平分割线 |

### 圆角和阴影

| 类名 | 说明 | 类名 | 说明 |
|------|------|------|------|
| `rounded` | border-radius: 0.25rem | `rounded-lg` | border-radius: 0.5rem |
| `rounded-full` | 完全圆角 | `shadow` | 阴影 |
| `shadow-lg` | 大阴影 | `shadow-none` | 无阴影 |

## 图标使用

### Iconify 图标

```html
<!-- Material Design Icons -->
<span class="i-mdi:home text-xl"></span>
<span class="i-mdi:account-circle text-2xl text-blue-500"></span>

<!-- Ant Design Icons -->
<span class="i-ant-design:home-outlined"></span>

<!-- 其他图标集 -->
<span class="i-carbon:home"></span>
<span class="i-ph:house"></span>
```

### 本地 SVG 图标

将 SVG 文件放入 `public/` 目录：

```html
<!-- 直接使用，i-svg:前缀 -->
<span class="i-svg:logo text-4xl"></span>
<span class="i-svg:obsidian-logo text-red-500"></span>
```

### @iconify/vue 组件

项目也支持使用组件方式：

```vue
<template>
  <Icon icon="mdi:home" />
  <Icon icon="mdi:home" :color="currentColor" :width="20" />
</template>

<script setup>
import { Icon } from '@iconify/vue';
</script>
```

## 动态类名

使用 UnoCSS 时需要注意，动态拼接的类名可能不会生效：

```vue
<template>
  <!-- ❌ 不推荐：动态拼接可能不生效 -->
  <div :class="`text-${color}-500`"></div>

  <!-- ✅ 推荐：使用完整类名 -->
  <div :class="color === 'red' ? 'text-red-500' : 'text-blue-500'"></div>

  <!-- ✅ 推荐：使用 unocss 的 safeList 或动态配置 -->
  <div :class="dynClass"></div>
</template>
```

## 自定义主题

在 `uno.config.ts` 中可以自定义主题：

```typescript
export default defineConfig({
  theme: {
    colors: {
      primary: '#0960bd',
      secondary: '#0084f4',
    },
    breakpoints: {
      'sm': '640px',
      'md': '768px',
    },
  },
});
```

使用：

```html
<div class="bg-primary text-secondary"></div>
```

## 响应式设计

```html
<!-- 默认移动优先，sm: 以上平板，md: 以上桌面 -->
<div class="
  w-full        <!-- 移动端：100% -->
  sm:w-1/2      <!-- 平板：50% -->
  md:w-1/3      <!-- 桌面：33.33% -->
"></div>
```

## 最佳实践

1. **与组件库配合**：优先使用组件库的样式，UnoCSS 用于布局和微调
2. **提取常用类**：将重复的工具类组合提取为组件
3. **避免过度嵌套**：原子化 CSS 的优势就是扁平化
4. **使用 preset-icons**：按需加载图标，减小包体积

## 相关链接

- [UnoCSS 官方文档](https://unocss.dev/)
- [Iconify 图标搜索](https://icones.js.org/)
- [预设图标集](https://github.com/iconify)
