UnoCSS

The instant on-demand atomic CSS engine.

README


UnoCSS

The instant on-demand Atomic CSS engine.

NPM version

💡 I highly recommend reading this blog post -
Reimagine Atomic CSS
for the story behind

🧑‍💻 Interactive Docs Beta |🤹‍♂️ Playground


Features


Inspired by Windi CSS, Tailwind CSS, and Twind, but:

- Fully customizable - no core utilities, all functionalities are provided via presets.
- No parsing, no AST, no scanning, it's INSTANT (5x faster than Windi CSS or Tailwind JIT).
- ~6kb min+brotli - zero deps and browser friendly.
- Shortcuts - aliasing utilities, dynamically.
- Attributify mode - group utilities in attributes.
- Pure CSS Icons - use any icon as a single class.
- Variant Groups - shorthand for group utils with common prefixes.
- CSS Directives - reuse utils in CSS with@apply directive.
- Compilation mode - synthesizes multiple classes into one at build time.
- Inspector - inspect and debug interactively.
- CSS-in-JS Runtime build - use UnoCSS with one line of CDN import.
- Code-splitting for CSS - ships minimal CSS for MPA.

Installation


- CLI

Configurations


UnoCSS is an atomic-CSS engine instead of a framework. Everything is designed with flexibility and performance in mind. There are no core utilities in UnoCSS, all functionalities are provided via presets.

By default, UnoCSS applies the default preset, which provides a common superset of the popular utilities-first frameworks Tailwind CSS, Windi CSS, Bootstrap, Tachyons, etc.

Presets


Presets are the heart of UnoCSS. They let you make your own custom framework in minutes.

Official Presets

- @unocss/preset-uno - The default preset (right now it's equivalent to@unocss/preset-wind).
- @unocss/preset-mini - The minimal but essential rules and variants.
- @unocss/preset-wind - Tailwind / Windi CSS compact preset.
- @unocss/preset-attributify - Provides Attributify Mode to other presets and rules.
- @unocss/preset-icons - Use any icon as a class utility.
- @unocss/preset-web-fonts - Web fonts at ease.
- @unocss/preset-typography - The typography preset.
- @unocss/preset-tagify - Tagify Mode for UnoCSS.
- @unocss/preset-rem-to-px - Converts rem to px for utils.

Community Presets

- unocss-preset-scalpel - Scalpel Preset by @macheteHot.
- unocss-preset-chroma - Gradient Preset by @chu121su12.
- unocss-preset-scrollbar - Scrollbar Preset by @action-hong.
- unocss-applet - Using UnoCSS in applet (UniApp / Taro) by @zguolee.
- unocss-preset-weapp - Wechat MiniProgram Preset for UniApp and Taro by @MellowCo.
- unocss-preset-extra - Animate.css Preset and some other rules by @Zhang-Wei-666.
- unocss-preset-daisy - daisyUI Preset by @kidonng.
- unocss-preset-primitives - Like headlessui-tailwindcss , radix-ui , custom for UnoCSS By @zirbest.
- unocss-preset-theme - Preset for automatic theme switching by @Dunqing

Community Frameworks

- Anu - DX focused utility based vue component library by @jd-solanki

Using Presets


To set presets to your project:

  1. ```ts
  2. // vite.config.ts
  3. import Unocss from 'unocss/vite'
  4. import { presetAttributify, presetUno } from 'unocss'

  5. export default {
  6.   plugins: [
  7.     Unocss({
  8.       presets: [
  9.         presetAttributify({ /* preset options */}),
  10.         presetUno(),
  11.         // ...custom presets
  12.       ],
  13.     }),
  14.   ],
  15. }
  16. ```

When the presets option is specified, the default preset will be ignored.

To disable the default preset, you can set presets to an empty array:

  1. ```ts
  2. // vite.config.ts
  3. import Unocss from 'unocss/vite'

  4. export default {
  5.   plugins: [
  6.     Unocss({
  7.       presets: [], // disable default preset
  8.       rules: [
  9.         // your custom rules
  10.       ],
  11.     }),
  12.   ],
  13. }
  14. ```

Custom Rules


Static Rules

Writing custom rules for UnoCSS is super easy. For example:

  1. ```ts
  2. rules: [
  3.   ['m-1', { margin: '0.25rem' }],
  4. ]
  5. ```

You will have the following CSS generated whenever m-1 is detected in users' codebase:

  1. ```css
  2. .m-1 { margin: 0.25rem; }
  3. ```

Dynamic Rules

To make it smarter, change the matcher to a RegExp and the body to a function:

  1. ```ts
  2. rules: [
  3.   [/^m-(\d+)$/, ([, d]) => ({ margin: `${d / 4}rem` })],
  4.   [/^p-(\d+)$/, match => ({ padding: `${match[1] / 4}rem` })],
  5. ]
  6. ```

The first argument of the body function is the match result, you can destructure it to get the matched groups.

For example, with the following usage:

  1. ``` html
  2. <div class="m-100">
  3.   <button class="m-3">
  4.     <icon class="p-5" />
  5.     My Button
  6.   </button>
  7. </div>
  8. ```

the corresponding CSS will be generated:

  1. ```css
  2. .m-100 { margin: 25rem; }
  3. .m-3 { margin: 0.75rem; }
  4. .p-5 { padding: 1.25rem; }
  5. ```

Congratulations! Now you got your own powerful atomic CSS utilities, enjoy!

Full Controlled Rules

This is an advanced feature, you don't need it in most of the cases.

When you really need some advanced rules that can't be covered by the combination of Dynamic Rules and Variants, we also provide a way to give you full control to generate the CSS.

By returning a string from the dynamic rule's body function, it will be directly passed to the generated CSS. That also means you would need to take care of things like CSS escaping, variants applying, CSS constructing, and so on.

  1. ```ts
  2. import Unocss, { toEscapedSelector as e } from 'unocss'

  3. Unocss({
  4.   rules: [
  5.     [/^custom-(.+)$/, ([, name], { rawSelector, currentSelector, variantHandlers, theme }) => {
  6.       // discard mismatched rules
  7.       if (name.includes('something'))
  8.         return

  9.       // if you want, you can disable the variants for this rule
  10.       if (variantHandlers.length)
  11.         return
  12.       const selector = e(rawSelector)
  13.       // return a string instead of an object
  14.       return `
  15. ${selector} {
  16.   font-size: ${theme.fontSize.sm};
  17. }
  18. /* you can have multiple rules */
  19. ${selector}::after {
  20.   content: 'after';
  21. }
  22. .foo > ${selector} {
  23.   color: red;
  24. }
  25. /* or media queries */
  26. @media (min-width: ${theme.breakpoints.sm}) {
  27.   ${selector} {
  28.     font-size: ${theme.fontSize.sm};
  29.   }
  30. }
  31. `
  32.     }],
  33.   ],
  34. })
  35. ```

You might need to read some code to take the full power of it.


Ordering


UnoCSS respects the order of the rules you defined in the generated CSS. Latter ones come with higher priority.

Shortcuts


The shortcuts functionality that UnoCSS provides is similar to Windi CSS's one


  1. ```ts
  2. shortcuts: {
  3.   // shortcuts to multiple utilities
  4.   'btn': 'py-2 px-4 font-semibold rounded-lg shadow-md',
  5.   'btn-green': 'text-white bg-green-500 hover:bg-green-700',
  6.   // single utility alias
  7.   'red': 'text-red-100'
  8. }
  9. ```

In addition to the plain mapping, UnoCSS also allows you to define dynamic shortcuts.

Similar to Rules, a dynamic shortcut is the combination of a matcher RegExp and a handler function.

  1. ```ts
  2. shortcuts: [
  3.   // you could still have object style
  4.   {
  5.     btn: 'py-2 px-4 font-semibold rounded-lg shadow-md',
  6.   },
  7.   // dynamic shortcuts
  8.   [/^btn-(.*)$/, ([, c]) => `bg-${c}-400 text-${c}-100 py-2 px-4 rounded-lg`],
  9. ]
  10. ```

With this, we could use btn-green and btn-red to generate the following CSS:

  1. ```css
  2. .btn-green {
  3.   padding-top: 0.5rem;
  4.   padding-bottom: 0.5rem;
  5.   padding-left: 1rem;
  6.   padding-right: 1rem;
  7.   --un-bg-opacity: 1;
  8.   background-color: rgba(74, 222, 128, var(--un-bg-opacity));
  9.   border-radius: 0.5rem;
  10.   --un-text-opacity: 1;
  11.   color: rgba(220, 252, 231, var(--un-text-opacity));
  12. }
  13. .btn-red {
  14.   padding-top: 0.5rem;
  15.   padding-bottom: 0.5rem;
  16.   padding-left: 1rem;
  17.   padding-right: 1rem;
  18.   --un-bg-opacity: 1;
  19.   background-color: rgba(248, 113, 113, var(--un-bg-opacity));
  20.   border-radius: 0.5rem;
  21.   --un-text-opacity: 1;
  22.   color: rgba(254, 226, 226, var(--un-text-opacity));
  23. }
  24. ```

Rules Merging


By default, UnoCSS will merge CSS rules with the same body to minimize the CSS size.

For example, `
` will generate

  1. ```css
  2. .hover\:m2:hover, .m-2 { margin: 0.5rem; }
  3. ```

instead of two separate rules:

  1. ```css
  2. .hover\:m2:hover { margin: 0.5rem; }
  3. .m-2 { margin: 0.5rem; }
  4. ```

Style Resetting


UnoCSS does not provide style resetting or preflight by default for maximum flexibility and does not populate your global CSS. If you use UnoCSS along with other CSS frameworks, they probably already do the resetting for you. If you use UnoCSS alone, you can use resetting libraries like Normalize.css.

We also provide a small collection for you to grab them quickly:

  1. ``` sh
  2. npm i @unocss/reset
  3. ```

  1. ```ts
  2. // main.js
  3. // pick one of the following

  4. // normalize.css
  5. import '@unocss/reset/normalize.css'
  6. // reset.css by Eric Meyer https://meyerweb.com/eric/tools/css/reset/index.html
  7. import '@unocss/reset/eric-meyer.css'
  8. // preflights from tailwind
  9. import '@unocss/reset/tailwind.css'
  10. ```

Learn more at @unocss/reset.

Preflight


You can inject raw css as preflights from the configuration. The resolved theme is available to customize the css.


  1. ```ts
  2. preflights: [
  3.   {
  4.     getCSS: ({ theme }) => `
  5.       * {
  6.         color: ${theme.colors.gray?.[700] ?? '#333'};
  7.         padding: 0;
  8.         margin: 0;
  9.       }
  10.     `
  11.   }
  12. ]
  13. ```

Custom Variants


Variants allows you to apply some variations to your existing rules. For example, to implement thehover: variant from Tailwind:


  1. ```ts
  2. variants: [
  3.   // hover:
  4.   (matcher) => {
  5.     if (!matcher.startsWith('hover:'))
  6.       return matcher
  7.     return {
  8.       // slice `hover:` prefix and passed to the next variants and rules
  9.       matcher: matcher.slice(6),
  10.       selector: s => `${s}:hover`,
  11.     }
  12.   }
  13. ],
  14. rules: [
  15.   [/^m-(\d)$/, ([, d]) => ({ margin: `${d / 4}rem` })],
  16. ]
  17. ```

- matcher controls when the variant is enabled. If the return value is a string, it will be used as the selector for matching the rules.
- selector provides the availability of customizing the generated CSS selector.

Let's have a tour of what happened when matching for hover:m-2:

- hover:m-2 is extracted from users usages
- hover:m-2 send to all variants for matching
- hover:m-2 is matched by our variant and returns m-2
- the result m-2 will be used for the next round of variants matching
- if no other variant is matched, m-2 will then goes to match the rules
- our first rule get matched and generates .m-2 { margin: 0.5rem; }
- finally, we apply our variants' transformation to the generated CSS. In this case, we prepended :hover to the selector hook

As a result, the following CSS will be generated:

  1. ```css
  2. .hover\:m-2:hover { margin: 0.5rem; }
  3. ```

With this, we could have m-2 applied only when users hover over the element.

The variant system is very powerful and can't be covered fully in this guide, you can check the default preset's implementation to see more advanced usages.

Extend Theme


UnoCSS also supports the theming system that you might be familiar with in Tailwind / Windi. At the user level, you can specify the theme property in your config, and it will be deep merged to the default theme.


  1. ```ts
  2. theme: {
  3.   // ...
  4.   colors: {
  5.     'veryCool': '#0000ff', // class="text-very-cool"
  6.     'brand': {
  7.       'primary': 'hsla(var(--hue, 217), 78%, 51%)', //class="bg-brand-primary"
  8.     }
  9.   },
  10. }
  11. ```

To consume the theme in rules:

  1. ```ts
  2. rules: [
  3.   [/^text-(.*)$/, ([, c], { theme }) => {
  4.     if (theme.colors[c])
  5.       return { color: theme.colors[c] }
  6.   }],
  7. ]
  8. ```

One exception is that UnoCSS gives full control of breakpoints to users. When a custom breakpoints is provided, the default will be overridden instead of merging. For example:


  1. ```ts
  2. theme: {
  3.   // ...
  4.   breakpoints: {
  5.     sm: '320px',
  6.     md: '640px',
  7.   },
  8. }
  9. ```

Right now, you can only use the sm: and md: breakpoint variants.

verticalBreakpoints is same as breakpoints but for vertical layout.

Layers


The order of CSS will affect their priorities. While we will retain the order of rules, sometimes you may want to group some utilities to have more explicit control of their order.

Unlike Tailwind, which offers 3 fixed layers (base, components, utilities), UnoCSS allows you to define the layers as you want. To set the layer, you can pass the metadata as the third item of your rules:

  1. ```ts
  2. rules: [
  3.   [/^m-(\d)$/, ([, d]) => ({ margin: `${d / 4}rem` }), { layer: 'utilities' }],
  4.   // when you omit the layer, it will be `default`
  5.   ['btn', { padding: '4px' }],
  6. ]
  7. ```

This will generate:

  1. ```css
  2. /* layer: default */
  3. .btn { padding: 4px; }
  4. /* layer: utilities */
  5. .m-2 { margin: 0.5rem; }
  6. ```

Layering also can be set on each preflight:

  1. ```ts
  2. preflights: [
  3.   {
  4.     layer: 'my-layer',
  5.     getCSS: async () => (await fetch('my-style.css')).text(),
  6.   },
  7. ]
  8. ```

You can control the order of layers by:


  1. ```ts
  2. layers: {
  3.   components: -1,
  4.   default: 1,
  5.   utilities: 2,
  6.   'my-layer': 3,
  7. }
  8. ```

Layers without specified order will be sorted alphabetically.

When you want to have your custom CSS between layers, you can update your entry module:

  1. ```ts
  2. // 'uno:[layer-name].css'
  3. import 'uno:components.css'
  4. // layers that are not 'components' and 'utilities' will fallback to here
  5. import 'uno.css'
  6. // your own CSS
  7. import './my-custom.css'
  8. // "utilities" layer will have the highest priority
  9. import 'uno:utilities.css'
  10. ```

Utilities Preprocess & Prefixing


UnoCSS also provides the ability to preprocess and transform extracted utilities before processing to the matcher. For example, the following example allows you to add a global prefix to all utilities:


  1. ```ts
  2. preprocess(matcher) {
  3.   return matcher.startsWith('prefix-')
  4.     ? matcher.slice(7)
  5.     : undefined // ignore
  6. }
  7. ```

Scanning


Please note that UnoCSS works at build time, meaning only statically presented utilities will be generated and shipped to your app. Utilities that used dynamically or fetched from external resources at runtime might not be applied.

By default, UnoCSS will extract the utilities usage from files in your build pipeline with extension .jsx, .tsx, .vue, .md, .html, .svelte, .astro. And then generate the CSS on demand.

.js and .ts files are NOT included by default. You can add @unocss-include, per-file basis, anywhere in the file that you want UnoCSS to scan, or add `.js or .ts in the configuration to include all js/ts files as scan targets. Similarly, you can also add @unocss-ignore` to bypass the scanning and transforming for a file.

Safelist


Sometimes you might want have to use dynamic concatenations like:

  1. ``` html
  2. <div class="p-${size}"></div> 
  3. ```

Due the fact that UnoCSS works in build time using static extracting, at the compile time we can't possibility know all the combination of the utilities. For that, you can configure the safelist option.

  1. ```ts
  2. safelist: 'p-1 p-2 p-3 p-4'.split(' ')
  3. ```

the corresponding CSS will always be generated:

  1. ```css
  2. .p-1 { padding: 0.25rem; }
  3. .p-2 { padding: 0.5rem; }
  4. .p-3 { padding: 0.75rem; }
  5. .p-4 { padding: 1rem; }
  6. ```

Or more flexible:

  1. ```ts
  2. safelist: [
  3.   ...Array.from({ length: 4 }, (_, i) => `p-${i + 1}`),
  4. ]
  5. ```

If you are seaking for the true dynamic generation at the runtime, you may check the @unocss/runtime package.

Inspector


From v0.7.0, our Vite plugin now ships with a dev inspector (@unocss/inspector) for you to view, play and analyse your custom rules and setup. Visithttp://localhost:3000/__unocss in your Vite dev server to see it.


Runtime (CSS-in-JS)



Acknowledgement


in alphabet order



Sponsors



License


MIT License © 2021-PRESENT Anthony Fu