Frontend Development 22 min read

UnoCSS Installation, Basic Usage, Presets, Transformers, and Common Tips

This article provides a comprehensive guide to UnoCSS, covering installation in Vue 3 + Vite and Nuxt 3 projects, basic syntax and interactive documentation, Iconify SVG integration, various presets and transformers, as well as practical shortcuts, responsive design, safelist handling, custom rules, theming, and dark‑mode support.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
UnoCSS Installation, Basic Usage, Presets, Transformers, and Common Tips

Preface

The author has been using UnoCSS in production for nearly two years and now shares a cleaned‑up training document with frequently used tricks, excluding internal project code.

Installation

In a Vue 3 + Vite project

Install UnoCSS:

pnpm add -D unocss

Register the plugin in vite.config.ts :

// vite.config.ts
import UnoCSS from 'unocss/vite'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [
    UnoCSS(),
  ],
})

Create uno.config.ts (or configure directly in vite.config.ts ):

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

export default defineConfig({
  // ...UnoCSS options
})

Import the generated CSS in main.ts :

// main.ts
import 'virtual:uno.css'

In Nuxt 3

Install the Nuxt module:

pnpm add -D @unocss/nuxt

Register it in nuxt.config.ts :

// nuxt.config.ts
export default defineNuxtConfig({
  modules: [
    '@unocss/nuxt',
  ],
})

Create uno.config.ts (or configure directly in nuxt.config.ts ):

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

export default defineConfig({
  // ...UnoCSS options
})

UnoCSS also supports React, Next, Remix, Astro, Svelte, Webpack, PostCSS Plugin, uni‑app, etc.

UnoCSS Basic Usage

Interactive Documentation

The interactive docs demonstrate utilities such as flex , width , colors , padding & margin , etc.

Basic Syntax

Example of a text element:

<div class="text-4xl font-600 font-italic underline lh-tight">
  文字
</div>

Border example:

<div class="border-2 rd-2xl border-dashed inline-block lh-10 text-4xl lh-20">
  文字
</div>

Margin example:

<!---->
<div class="p-x-4 py-8 mb-2 mt-3 inline-block border-2">
  边距
</div>

Width/height example:

<div class="w-40 h-30 border-2 py-2">
  <div class="h-full w-screen border-dashed border-1">宽高</div>
</div>

Color example:

<div class="w-40 h-30 bg-stone p-2">
  <div class="bg-pink op-30 mb-2">背景</div>
  <div class="bg-blue color-green p-2">颜色</div>
</div>

Flex layout example:

<div class="w-xs">
  <h1 class="mb-2">Flex 布局</h1>
  <div class="flex items-center justify-between border-1 mb-1 px-1">
    <div>flex-1</div>
    <div>flex-2</div>
    <div>flex-3</div>
  </div>
  <div class="flex items-center justify-end gap-3 border-1 mb-1 px-1">
    <div>flex-1</div>
    <div>flex-2</div>
    <div>flex-3</div>
  </div>
  <div class="flex flex-col gap-1 border-1 px-1">
    <div>flex-1</div>
    <div>flex-2</div>
  </div>
</div>

Positioning example:

<div class="w-xs border-1 p-2 relative">
  父元素
  <div class="absolute top-2 right-10 zindex-100">子元素</div>
</div>

Animation example:

<div class="border-1 relative w-40 hover:transform-rotate-50 transition-all">
  <div class="transform-rotate-10 translate-x-10 cursor-pointer">动画</div>
</div>

Important rule example:

<div class="w-xs border-1 p-2 text-4xl">
  父元素
  <div class="!text-2xl">子元素</div>
</div>

IDE Plugin Hints

Shows how IDE extensions can provide autocomplete and preview for UnoCSS classes.

Iconify SVG

Official documentation: https://iconify.design/

Icon sets: https://icon-sets.iconify.design/ and https://icones.js.org/

Installation

pnpm add -D @unocss/preset-icons @iconify-json/[the-collection-you-want]

Common collections: @iconify-json/carbon and @iconify-json/remix .

To download the full icon set (≈130 MB):

pnpm add -D @iconify/json

Configure the preset in uno.config.ts :

presetIcons({
  extraProperties: {
    prefix: 'i-',
    display: 'inline-block',
    'vertical-align': 'middle',
    // ...
  },
})

Using SVG Icons

Basic usage via class:

<div class="p-4">
  <div class="i-carbon-3d-curve-auto-colon" />
</div>

Adjust size:

<div class="p-4 flex items-center">
  <div class="i-ri-bluesky-line text-3xl" />
</div>

Change color:

<div class="p-4 flex items-center">
  <div class="i-ri-bluesky-line text-3xl color-blue" />
</div>

Hover effect:

<div class="text-3xl i-twemoji-grinning-face-with-smiling-eyes hover:i-twemoji-face-with-tears-of-joy" />

Local SVG Compression

Install svgo globally and run:

pnpm add -g svgo
svgo -f path -o path

UnoCSS Presets

Icons preset

Enables SVG icon usage as shown above.

// uno.config.ts
import { defineConfig, presetIcons } from 'unocss'

export default defineConfig({
  presets: [
    presetIcons({ /* options */ }),
    // ...other presets
  ],
})

Common options: scale , prefix , extraProperties .

presetIcons({
  scale: 1.2,
  prefix: 'i-',
  extraProperties: {
    display: 'inline-block',
  },
})

Attributify preset

Allows writing utilities as HTML attributes.

// uno.config.ts
import { defineConfig, presetAttributify } from 'unocss'

export default defineConfig({
  presets: [
    presetAttributify({ /* options */ }),
    // ...
  ],
})

Example button without a class attribute:

<button
  w-50
  bg="blue-400 hover:blue-500 dark:blue-500 dark:hover:blue-600"
  text="sm white"
  font="mono light"
  p="y-2 x-4 l-2 r-2 b-2 t-2"
  border="2 rounded blue-200"
>我不需要写 class</button>

When a component’s own prop conflicts, prefix with un- :

<MyText text="red">与组件的 text 属性冲突</MyText>
<MyText un-text="red">使用前缀设置颜色,不会冲突</MyText>

Web Fonts preset

Provides easy font loading.

// uno.config.ts
import { defineConfig, presetWebFonts } from 'unocss'

export default defineConfig({
  presets: [
    presetWebFonts({ /* options */ }),
  ],
})

Typical configuration:

presetWebFonts({
  fonts: {
    sans: 'Inter:400,600,800',
    mono: 'DM Mono:400,600',
  },
})

Custom fetch (e.g., via Axios with a proxy) can be defined with customFetch .

Rem to px preset

Converts all rem values (base 16 px) to px when needed.

// uno.config.ts
import { defineConfig, presetRemToPx } from 'unocss'

export default defineConfig({
  presets: [
    presetRemToPx(),
    // ...other presets
  ],
})

UnoCSS Transformers

Variant group transformer

Groups multiple utilities under a single variant.

// uno.config.ts
import { defineConfig, transformerVariantGroup } from 'unocss'

export default defineConfig({
  transformers: [
    transformerVariantGroup(),
  ],
})
<div class="hover:(bg-gray-400 font-medium) font-(light mono)"/>

Expands to:

<div class="hover:bg-gray-400 hover:font-medium font-light font-mono"/>

Directives transformer

Allows using atomic utilities inside CSS with @apply or --at-apply .

.custom-div {
  @apply text-center my-0 font-medium;
}
/* or */
.custom-div {
  --at-apply: text-center my-0 font-medium;
}

Attributify JSX transformer

Enables attribute‑style utilities in JSX/TSX.

// uno.config.ts
import { defineConfig, presetAttributify, transformerAttributifyJsx } from 'unocss'

export default defineConfig({
  presets: [presetAttributify()],
  transformers: [transformerAttributifyJsx()],
})
export function Component() {
  return (
unocss
)
}

Compile class transformer

Compiles grouped classes into a single generated class.

// uno.config.ts
import { defineConfig, transformerCompileClass } from 'unocss'

export default defineConfig({
  transformers: [
    transformerCompileClass(),
  ],
})
<div class=":uno: text-center sm:text-left">
  <div class=":uno: text-sm font-bold hover:text-red"/>
</div>

Compiled output:

.uno-qlmcrp { text-align: center; }
.uno-0qw2gr { font-size: 0.875rem; line-height: 1.25rem; font-weight: 700; }
.uno-0qw2gr:hover { --un-text-opacity: 1; color: rgb(248 113 113 / var(--un-text-opacity)); }
@media (min-width: 640px) { .uno-qlmcrp { text-align: left; } }

Common UnoCSS Tips

Shortcuts (combined classes)

Combine multiple utilities into a single class for global themes, backgrounds, etc.

export default defineConfig({
  shortcuts: [
    {
      'bg-main': 'bg-hex-eef5fc dark:bg-hex-0d1117',
      'text-main': 'text-hex-555555 dark:text-hex-bbbbbb',
      // ...more shortcuts
    },
    {
      'text-title': 'text-link text-4xl font-800',
      // ...more shortcuts
    },
  ]
})

Responsive Styles

Use prefixes like sm: , lg: , xl: to apply utilities at breakpoints (sm = 640 px, lg = 1024 px, xl = 1280 px).

<nav class="sm:flex hidden flex-wrap gap-x-6">…</nav>
<div sm:hidden …>…</div>

Safelist and Dynamic Icon Loading

Pre‑load icons that are used dynamically:

export default defineConfig({
  safelist: [
    'i-ri-file-list-2-line',
    'i-carbon-campsite',
  ],
})

Or store class names in a map and reference them at runtime.

Custom Class Rules

Override or add rules via rules :

rules: [
  ['font-bold', { 'font-weight': 700 }],
  [/^m-(\d+)$/, ([, d]) => ({ margin: `${d / 4}rem` })],
]

Define shortcuts with regex for dynamic generation:

shortcuts: {
  'btn': 'py-2 px-4 font-semibold rounded-lg shadow-md',
  'btn-green': 'btn text-white bg-green-500 hover:bg-green-700',
  [/^btn-(.*)$/, ([, c]) => `bg-${c}-400 text-${c}-100 py-2 px-4 rounded-lg`],
}

Custom Theme and Overrides

Extend or replace the default theme:

theme: {
  colors: {
    veryCool: '#0000ff',
    brand: {
      primary: 'hsl(var(--hue, 217) 78% 51%)',
    },
  },
  breakpoints: {
    sm: '320px',
    md: '640px',
  },
}

Use the custom colors in markup:

<div class="bg-brand-primary">
  <a class="color-brand-primary">链接</a>
</div>

Class Custom Color Values

Directly specify hex colors in utilities, e.g., class="bg-#000 bg-hex-fff" or via attribute syntax bg="#000" .

Dark Mode with VueUse

Toggle dark mode using an icon:

<i i="carbon-sun dark:carbon-moon" @click="toggleDark()" />

Common Class Shorthands

Flex shorthand: <div flex="~ items-center gap-2" />

Margin/padding shorthand: <div m-1 ml-1 mx-1 m-x-1 mt-1 mt-1.5px m="1 0" />

Width/height shorthand: <div h-1 h-auto h-full h-screen min-h-1 min-h-2vw max-h-50px />

Negative values: <div h--1 h--10px m--1 />

Rounded corners: <div rounded rd-1 rd-full rd="1 0" />

Important flag: <div !flex />

Cursor style: <div cursor-pointer />

Disabled state: <div disabled:cursor-default />

frontendVuetransformersviteNuxtPresetsUnoCSSCSS Utility
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.