跳到内容
SCRM DOC

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

前端UnoCSS样式创建于2025-03-22更新于 2025-03-22

UnoCSS 使用指南

UnoCSS 是一个即时的原子化 CSS 引擎,比 Tailwind CSS/WindiCSS 更快、更轻量。

项目配置

配置文件

项目根目录 uno.config.ts:

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 可以完美共存:

<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-4padding: 1remm-4margin: 1rem
px-2padding-x: 0.5rempy-1padding-y: 0.25rem
mt-2margin-top: 0.5remmb-4margin-bottom: 1rem

尺寸

类名说明类名说明
w-fullwidth: 100%h-screenheight: 100vh
w-1/2width: 50%h-10height: 2.5rem
max-w-mdmax-width: 28remmin-h-screenmin-height: 100vh

文字

类名说明类名说明
text-smfont-size: 0.875remtext-lgfont-size: 1.125rem
font-boldfont-weight: 700font-normalfont-weight: 400
text-centertext-align: centertext-lefttext-align: left
truncate文本溢出省略line-clamp-2限制2行

颜色

类名说明类名说明
bg-whitebackground: whitebg-blue-500background: #3b82f6
text-blackcolor: blacktext-red-500color: #ef4444
border-gray-200border-color: #e5e7ebdivide-y水平分割线

圆角和阴影

类名说明类名说明
roundedborder-radius: 0.25remrounded-lgborder-radius: 0.5rem
rounded-full完全圆角shadow阴影
shadow-lg大阴影shadow-none无阴影

图标使用

Iconify 图标

<!-- 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/ 目录:

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

@iconify/vue 组件

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

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

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

动态类名

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

<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 中可以自定义主题:

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

使用:

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

响应式设计

<!-- 默认移动优先,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:按需加载图标,减小包体积

相关链接

页面信息›
已优化是

本页目录