# Unocss
> Autocomplete can be customized for UnoCSS's intelligent suggestions in playground and the [VS Code extension](/integrations/vscode).
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/config/autocomplete.md
# Path: docs/config/autocomplete.md
# Autocomplete
Autocomplete can be customized for UnoCSS's intelligent suggestions in playground and the [VS Code extension](/integrations/vscode).
```ts
autocomplete: {
templates: [
// theme inferring
'bg-$color/',
// short hands
'text-',
// logic OR groups
'(b|border)-(solid|dashed|dotted|double|hidden|none)',
// constants
'w-half',
],
shorthands: {
// equal to `opacity: "(0|10|20|30|40|50|60|70|90|100)"`
'opacity': Array.from({ length: 11 }, (_, i) => i * 10),
'font-size': '(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)',
// override built-in short hands
'num': '(0|1|2|3|4|5|6|7|8|9)',
},
extractors: [
// ...extractors
],
}
```
- `templates` uses a simple DSL to specify the autocomplete suggestions.
- `shorthands` is a map of shorthand names to their templates. If it's a `Array`, it will be a logic OR group.
- `extractors` to pickup possible classes and transform class-name style suggestions to the correct format. For example, you could check how we implement the [attributify autocomplete extractor](https://github.com/unocss/unocss/blob/main/packages-presets/preset-attributify/src/autocomplete.ts)
- For additional help, please refer to [here](/tools/autocomplete).
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/config/extractors.md
# Path: docs/config/extractors.md
# Extractors
Extractors are used to extract the usage of utilities from your source code.
```ts [uno.config.ts]
import { defineConfig } from 'unocss'
export default defineConfig({
extractors: [
// your extractors
],
})
```
By default [extractorSplit](https://github.com/unocss/unocss/blob/main/packages-engine/core/src/extractors/split.ts) will always be applied, which splits the source code into tokens and directly feed to the engine.
To override the default extractors, you can use `extractorDefault` option.
```ts [uno.config.ts]
import { defineConfig } from 'unocss'
export default defineConfig({
extractors: [
// your extractors
],
// disable the default extractor
extractorDefault: false,
// override the default extractor with your own
extractorDefault: myExtractor,
})
```
For example, please check the implementation of [pug extractor](https://github.com/unocss/unocss/blob/main/packages-presets/extractor-pug/src/index.ts) or the [attributify extractor](https://github.com/unocss/unocss/blob/main/packages-presets/preset-attributify/src/extractor.ts).
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/config/index.md
# Path: docs/config/index.md
---
title: Configuring UnoCSS
description: Configurations are what make UnoCSS powerful.
outline: deep
---
# Configuring UnoCSS
## Configuration
Configurations are what make UnoCSS powerful.
- [Rules](/config/rules) - Define atomic CSS utilities
- [Shortcuts](/config/shortcuts) - Combine multiple rules into a single shorthand.
- [Theme](/config/theme) - Define theme variables.
- [Variants](/config/variants) - Apply custom conventions to rules.
- [Extractors](/config/extractors) - Define where and how the usage of utilities are extracted.
- [Preflights](/config/preflights) - Define global raw CSS.
- [Layers](/config/layers) - Define the order of each utilities layer.
- [Presets](/config/presets) - Predefined configurations for common use cases.
- [Transformers](/config/transformers) - Code transformers to user sources code to support conventions.
- [Autocomplete](/config/autocomplete) - Define customized autocomplete suggestions.
## Options
### rules
- **Type:** `Rule[]`
Rules to generate CSS utilities. Later entries have higher priority.
### shortcuts
- **Type:** `UserShortcuts`
Similar to Windi CSS's shortcuts, allows you to create new utilities by combining existing ones. Later entries have higher priority.
### theme
- **Type:** `Theme`
Theme object for shared configuration between rules.
### extendTheme
- **Type:** `Arrayable>`
Custom functions mutate the theme object.
It's also possible to return a new theme object to completely replace the original one.
### variants
- **Type:** `Variant[]`
Variants that preprocess the selectors, having the ability to rewrite the CSS object.
### extractors
- **Type:** `Extractor[]`
Extractors to handle the source file and output possible classes/selectors. Can be language-aware.
### preflights
- **Type:** `Preflight[]`
Raw CSS injections.
### layers
- **Type:** `Record`
Layer orders. Default to 0.
### outputToCssLayers
- **Type:** `boolean | UseCssLayersOptions`
- **Default:** `false`
Outputs the layers to CSS Cascade Layers.
#### cssLayerName
- **Type:** `(internalLayer: string) => string | undefined | null`
Specifies the name of the CSS layer the internal layer should be output to (can be a sublayer e.g. "mylayer.mysublayer").
If `undefined` is return, the internal layer name wil be used as the CSS layer name.
If `null` is return, the internal layer will not be output to a CSS layer.
### sortLayers
- **Type:** `(layers: string[]) => string[]`
Custom function to sort layers.
### presets
- **Type:** `(PresetOrFactory | PresetOrFactory[])[]`
Predefined configurations for common use cases.
### transformers
- **Type:** `SourceCodeTransformer[]`
Custom transformers to the source code.
### blocklist
- **Type:** `BlocklistRule[]`
Rules to exclude the selectors for your design system (to narrow down the possibilities). Combining `warnExcluded` options can also help you identify wrong usages.
### safelist
- **Type:** `string[]`
Utilities that are always included.
### preprocess
- **Type:** `Arrayable`
Preprocess the incoming utilities, return falsy value to exclude.
### postprocess
- **Type:** `Arrayable`
Postprocess the generate utils object.
### separators
- **Type:** `Arrayable`
- **Default:** `[':', '-']`
Variant separator.
### extractorDefault
- **Type:** `Extractor | null | false`
- **Default:** `import('@unocss/core').defaultExtractor`
Default extractor that are always applied. By default it split the source code by whitespace and quotes.
It maybe be replaced by preset or user config, only one default extractor can be presented, later one will override the previous one.
Pass `null` or `false` to disable the default extractor.
### autocomplete
Additional options for auto complete.
#### templates
- **Type:** `Arrayable`
Custom functions / templates to provide autocomplete suggestions.
#### extractors
- **Type:** `Arrayable`
Custom extractors to pickup possible classes and transform class-name style suggestions to the correct format.
#### shorthands
- **Type:** `Record`
Custom shorthands to provide autocomplete suggestions. if values is an array, it will be joined with `|` and wrapped with `()`.
### content
Options for sources to be extracted as utilities usages.
Supported sources:
- `filesystem` - extract from file system
- `inline` - extract from plain inline text
- `pipeline` - extract from build tools' transformation pipeline, such as Vite and Webpack
The usage extracted from each source will be **merged** together.
#### filesystem
- **Type:** `string[]`
- **Default:** `[]`
Glob patterns to extract from the file system, in addition to other content sources. `node_modules` are ignored by default, but unocss will scan from it when you specify the path includes `node_modules`.
In dev mode, the files will be watched and trigger HMR.
#### inline
- **Type:** `string | { code: string; id?: string } | (() => Awaitable)) []`
Inline text to be extracted.
#### pipeline
Filters to determine whether to extract certain modules from the build tools' transformation pipeline.
Currently only works for Vite and Webpack integration.
Set `false` to disable.
##### include
- **Type:** `FilterPattern`
- **Default:** `[/\.(vue|svelte|[jt]sx|vine.ts|mdx?|astro|elm|php|phtml|html)($|\?)/]`
Patterns that filter the files being extracted. Supports regular expressions and `picomatch` glob patterns.
By default, `.ts` and `.js` files are NOT extracted.
##### exclude
- **Type:** `FilterPattern`
- **Default:** `[/\.(css|postcss|sass|scss|less|stylus|styl)($|\?)/]`
Patterns that filter the files NOT being extracted. Supports regular expressions and `picomatch` glob patterns.
By default, `node_modules` and `dist` are also extracted.
### configResolved
- **Type:** `(config: ResolvedConfig) => void`
Hook to modify the resolved config.
First presets runs first and the user config.
### configFile
- **Type:** `string | false`
Load from configs files.
Set `false` to disable.
### configDeps
- **Type:** `string[]`
List of files that will also trigger config reloads.
### cli
UnoCSS CLI options.
#### entry
- **Type:** `Arrayable`
UnoCSS cli entry points.
##### patterns
- **Type:** `string[]`
Glob patterns to extract from the file system.
##### outFile
- **Type:** `string`
Output file path.
### shortcutsLayer
- **Type:** `string`
- **Default:** `'shortcuts'`
Layout name of shortcuts.
### envMode
- **Type:** `'dev' | 'build'`
- **Default:** `'build'`
Environment mode.
### details
- **Type:** `boolean`
Expose internal details for debugging / inspecting.
### warn
- **Type:** `boolean`
- **Default:** `true`
Emit warning when matched selectors are presented in blocklist.
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/config/layers.md
# Path: docs/config/layers.md
---
title: Layers
icon: ph:stack-bold
description: UnoCSS allows you to define the layers as you want.
---
# Layers
The order of CSS will affect their priorities. While the engine will [retain the order of rules](/config/rules#ordering), sometimes you may want to group some utilities to have explicit control of their order.
## Usage
Unlike Tailwind CSS which offers three 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:
```ts
rules: [
[/^m-(\d)$/, ([, d]) => ({ margin: `${d / 4}rem` }), { layer: 'utilities' }],
// when you omit the layer, it will be `default`
['btn', { padding: '4px' }],
]
```
This will generate:
```css
/* layer: default */
.btn { padding: 4px; }
/* layer: utilities */
.m-2 { margin: 0.5rem; }
```
Layer also can be set on each preflight:
```ts
preflights: [
{
layer: 'my-layer',
getCSS: async () => (await fetch('my-style.css')).text(),
},
]
```
## Ordering
You can control the order of layers by:
```ts
layers: {
'components': -1,
'default': 1,
'utilities': 2,
'my-layer': 3,
}
```
Layers without specified order will be sorted alphabetically.
When you want to have your custom CSS between layers, you can update your entry module:
```ts
// 'uno:[layer-name].css'
import 'uno:components.css'
// layers that are not 'components' and 'utilities' will fallback to here
import 'uno.css'
// your own CSS
import './my-custom.css'
// "utilities" layer will have the highest priority
import 'uno:utilities.css'
```
## CSS Cascade Layers
You can output CSS Cascade Layers by:
```ts
outputToCssLayers: true
```
You can change the CSS Layer names with:
```ts
outputToCssLayers: {
cssLayerName: (layer) => {
// The default layer will be output to the "utilities" CSS layer.
if (layer === 'default')
return 'utilities'
// The shortcuts layer will be output to the "shortcuts" sublayer the of "utilities" CSS layer.
if (layer === 'shortcuts')
return 'utilities.shortcuts'
// All other layers will just use their name as the CSS layer name.
}
}
```
## Layers using variants
Layers can be created using variants.
`uno-layer-:` can be used to create a UnoCSS layer.
```html
text
```
```css
/* layer: my-layer */
.uno-layer-my-layer\:text-xl{ font-size:1.25rem; line-height:1.75rem; }
```
`layer-:` can be used to create a CSS @layer.
```html
text
```
```css
/* layer: default */
@layer my-layer{ .layer-my-layer\:text-xl{ font-size:1.25rem; line-height:1.75rem; } }
```
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/config/preflights.md
# Path: docs/config/preflights.md
---
title: Preflights
description: You can inject raw CSS as preflights from the configuration. The resolved theme is available to customize the CSS.
---
# Preflights
You can inject raw CSS as preflights from the configuration. The resolved `theme` is available to customize the CSS.
```ts
preflights: [
{
getCSS: ({ theme }) => `
* {
color: ${theme.colors.gray?.[700] ?? '#333'};
padding: 0;
margin: 0;
}
`,
},
]
```
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/config/presets.md
# Path: docs/config/presets.md
# Presets
Presets are partial configurations that will be merged into the main configuration.
When authoring a preset, we usually export a constructor function that you could ask for some preset-specific options. For example:
```ts [my-preset.ts]
import { definePreset, Preset } from 'unocss'
export default definePreset((options?: MyPresetOptions) => {
return {
name: 'my-preset',
rules: [
// ...
],
variants: [
// ...
],
// it supports most of the configuration you could have in the root config
}
})
```
Then the user can use it like this:
```ts [uno.config.ts]
import { defineConfig } from 'unocss'
import myPreset from './my-preset'
export default defineConfig({
presets: [
myPreset({ /* preset options */ }),
],
})
```
You can check [official presets](/presets/) and [community presets](/presets/community) for more examples.
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/config/rules.md
# Path: docs/config/rules.md
---
title: Rules
description: Writing custom rules for UnoCSS is super easy.
---
# Rules
Rules define utility classes and the resulting CSS. UnoCSS has many built-in rules but also allows for easily adding custom rules.
## Static rules
With this example:
```ts
rules: [
['m-1', { margin: '0.25rem' }],
]
```
The following CSS will be generated whenever `m-1` is detected in users' codebase:
```css
.m-1 {
margin: 0.25rem;
}
```
> **Note**: The body syntax follows CSS property syntax, eg. `font-weight` instead of `fontWeight`. If there is a hyphen `-` in the property name it should be quoted.
>
> ```ts
> rules: [
> ['font-bold', { 'font-weight': 700 }],
> ]
> ```
## Dynamic rules
To make it smarter, change the matcher to a `RegExp` and the body to a function:
```ts
rules: [
[/^m-(\d+)$/, ([, d]) => ({ margin: `${d / 4}rem` })],
// You can get rich context information from the second argument, such as `theme`, `symbols`, etc.
[/^p-(\d+)$/, (match, ctx) => ({ padding: `${match[1] / 4}rem` })],
]
```
The first argument of the body function is the `RegExp` match result that can be destructured to get the matched groups.
For example, with the following usage:
```html
```
the corresponding CSS will be generated:
```css
.m-100 { margin: 25rem; }
.m-3 { margin: 0.75rem; }
.p-5 { padding: 1.25rem; }
```
Congratulations! Now you've got your own powerful atomic CSS utilities. Enjoy!
## CSS Rules Fallback
In cases you might want to leverage CSS rules fallback to use new CSS features while also able to fallback to support old browsers, you can optionally return a 2D-array as the CSS representation for rules with the same keys. For example:
```ts
rules: [
[/^h-(\d+)dvh$/, ([_, d]) => {
return [
['height', `${d}vh`],
['height', `${d}dvh`],
]
}],
]
```
Which will make `h-100dvh` generates:
```css
.h-100dvh { height: 100vh; height: 100dvh; }
```
## Special symbols
Since v0.61, UnoCSS supports special symbols to define additional meta information for your generated CSS. You can access the symbols from the `symbols` object from `@unocss/core` or the second argument of the dynamic rule matcher function.
For example:
::: code-group
```ts [Static Rules]
import { symbols } from '@unocss/core'
rules: [
['grid', {
[symbols.parent]: '@supports (display: grid)',
display: 'grid',
}],
]
```
```ts [Dynamic Rules]
rules: [
[/^grid$/, ([, d], { symbols }) => {
return {
[symbols.parent]: '@supports (display: grid)',
display: 'grid',
}
}],
]
```
:::
Will generate:
```css
@supports (display: grid) {
.grid {
display: grid;
}
}
```
:::tip
If you know exactly how a rule is generated, we recommend using **static rules** to improve UnoCSS performance.
:::
### Available symbols
| Symbols | Description |
| -------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `symbols.parent` | The parent wrapper of the generated CSS rule (e.g., `@supports`, `@media`, etc.) |
| `symbols.selector` | A function to modify the selector of the generated CSS rule (see example below) |
| `symbols.layer` | Sets the UnoCSS layer of the generated CSS rule (can be string, function, or regex match) |
| `symbols.variants` | An array of variant handlers applied to the current CSS object |
| `symbols.shortcutsNoMerge` | Boolean to disable merging of the current rule in shortcuts |
| `symbols.noMerge` | Boolean to disable merging of the current rule |
| `symbols.sort` | Number to overwrite sorting order of the current CSS object |
| `symbols.body` | Fully control the body of the generated CSS rule (see [#4889](https://github.com/unocss/unocss/pull/4889)) |
## Multi-selector rules
Since v0.61, UnoCSS supports multi-selector via [JavaScript Generator functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator). And generates _multiple_ CSS rules from a _single_ rule.
For example:
::: code-group
```ts [Static Rules]
rules: [
['button-red', [
{ background: 'red' },
{
[symbols.selector]: selector => `${selector}:hover`,
// https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/color-mix
background: `color-mix(in srgb, red 90%, black)`
},
]],
]
```
```ts [Dynamic Rules]
rules: [
[/^button-(.*)$/, function* ([, color], { symbols }) {
yield {
background: color
}
yield {
[symbols.selector]: selector => `${selector}:hover`,
// https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/color-mix
background: `color-mix(in srgb, ${color} 90%, black)`
}
}],
]
```
:::
Will generate multiple CSS rules:
```css
.button-red {
background: red;
}
.button-red:hover {
background: color-mix(in srgb, red 90%, black);
}
```
## Fully controlled rules
::: tip
This is an advanced feature, in most situtations it won't be needed.
:::
When you really need some advanced rules that aren't covered by the combination of [Dynamic Rules](#dynamic-rules) and [Variants](/config/variants), UnoCSS also provides a way to give you full control to generate the CSS.
It allows you to return a string from the dynamic rule's body function which will be **directly** passed to the generated CSS (this also means you need to take care of things like CSS escaping, variant applying, CSS constructing, and so on).
```ts [uno.config.ts]
import { defineConfig, toEscapedSelector as e } from 'unocss'
export default defineConfig({
rules: [
[/^custom-(.+)$/, ([, name], { rawSelector, currentSelector, variantHandlers, theme }) => {
// discard mismatched rules
if (name.includes('something'))
return
// if you want, you can disable the variants for this rule
if (variantHandlers.length)
return
const selector = e(rawSelector)
// return a string instead of an object
return `
${selector} {
font-size: ${theme.fontSize.sm};
}
/* you can have multiple rules */
${selector}::after {
content: 'after';
}
.foo > ${selector} {
color: red;
}
/* or media queries */
@media (min-width: ${theme.breakpoints.sm}) {
${selector} {
font-size: ${theme.fontSize.sm};
}
}
`
}],
],
})
```
::: warning
The above method can fully control the generated CSS, but it cannot be extended through `variants`, losing the flexibility brought by its variant.
e.g. `hover:custom-xxx` -> The `hover` variant won't work.
:::
So if you want to fully customize the output while still enjoying the convenience of variants, you can consider using `symbols.body` to achieve this.
::: code-group
```ts [Static Rules]
import { symbols } from '@unocss/core'
rules: [
['custom-red', {
// symbols.body doesn't need `{}` wrapping the styles
[symbols.body]: `
font-size: 1rem;
&::after {
content: 'after';
}
& > .bar {
color: red;
}
`,
[symbols.selector]: selector => `:is(${selector})`,
}]
]
```
```ts [Dynamic Rules]
rules: [
[/^custom-(.+)$/, ([_, c], { symbols }) => {
return {
[symbols.body]: `
font-size: 1rem;
&::after {
content: 'after';
}
& > .bar {
color: ${c};
}
`,
[symbols.selector]: selector => `:is(${selector})`,
}
}]
]
```
:::
Will generate fully CSS rules from `hover:custom-red`:
```css
:is(.hover\:custom-red):hover {
font-size: 1rem;
&::after {
content: 'after';
}
& > .bar {
color: red;
}
}
```
## Ordering
UnoCSS respects the order of the rules you defined in the generated CSS. Latter ones come with higher priority.
When using dynamic rules, it may match multiple tokens. By default, the output of those matched under a single dynamic rule will be sorted alphabetically within the group.
## Rules merging
By default, UnoCSS will merge CSS rules with the same body to minimize the CSS size.
For example, `
` will generate:
```css
.hover\:m2:hover,
.m-2 {
margin: 0.5rem;
}
```
Instead of two separate rules:
```css
.hover\:m2:hover {
margin: 0.5rem;
}
.m-2 {
margin: 0.5rem;
}
```
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/config/safelist.md
# Path: docs/config/safelist.md
# Safelist
Safelist is an important option in UnoCSS configuration that allows you to specify a set of utility classes that should always be included in the generated CSS, regardless of whether these classes are detected in your source code.
## Basic Usage
### String Array
The simplest usage is to provide a string array containing the class names you want to preserve:
```ts
// uno.config.ts
export default defineConfig({
safelist: [
'p-1',
'p-2',
'p-3',
'text-center',
'bg-red-500'
]
})
```
### Function Form
Safelist can also contain functions that are called during build time and can dynamically return class names:
```ts
// uno.config.ts
export default defineConfig({
safelist: [
// Static class names
'p-1',
'p-2',
// Dynamic function
context => ['m-1', 'm-2', 'm-3'],
(context) => {
// Generate class names based on theme
const colors = Object.keys(context.theme.colors || {})
return colors.map(color => `bg-${color}-500`)
}
]
})
```
### Mixed Usage
You can mix strings and functions in the same safelist configuration:
```ts
// uno.config.ts
export default defineConfig({
safelist: [
// Static class names
'prose',
'bg-orange-300',
// Dynamic generation
() => ['flex', 'grid', 'block'],
// Conditional dynamic generation
(context) => {
if (process.env.NODE_ENV === 'development') {
return ['debug-border', 'debug-grid']
}
return []
}
]
})
```
## Return Value Types
Safelist functions can return the following types of values:
- `Arrayable` - String or string array
```ts
safelist: [
// Return string array
() => ['class1', 'class2', 'class3'],
// Return single string
() => 'single-class',
// Return nested array (will be flattened)
() => [['nested1', 'nested2'], 'normal3']
]
```
## Practical Use Cases
### Dynamically Generated Class Names
When you have dynamically generated class names that might not be detected by static analysis:
```ts
safelist: [
// Dynamic color classes
() => {
const dynamicColors = ['primary', 'secondary', 'accent']
return dynamicColors.flatMap(color => [
`bg-${color}`,
`text-${color}`,
`border-${color}`
])
},
// Dynamic size classes
() => {
return Array.from({ length: 12 }, (_, i) => `gap-${i + 1}`)
}
]
```
### Third-party Component Library Support
Provide necessary class names for third-party component libraries:
```ts
safelist: [
// Reserved class names for component library
'prose',
'prose-sm',
'prose-lg',
// Dynamically generate component variants
() => {
const variants = ['primary', 'secondary', 'danger', 'success']
const sizes = ['sm', 'md', 'lg']
return variants.flatMap(variant =>
sizes.map(size => `btn-${variant}-${size}`)
)
}
]
```
## Relationship with Other Configurations
### Difference from blocklist
- **safelist**: Ensures specified class names are always included
- **blocklist**: Ensures specified class names are always excluded
```ts
export default defineConfig({
safelist: ['always-include'],
blocklist: ['never-include']
})
```
### Relationship with Generation Options
When generating CSS, you can control whether to include safelist through `GenerateOptions`:
```ts
const { css } = await uno.generate('', {
safelist: true // Include class names from safelist
})
```
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/config/shortcuts.md
# Path: docs/config/shortcuts.md
---
title: Shortcuts
description: The shortcuts functionality that UnoCSS provides is similar to Windi CSS's one.
---
# Shortcuts
Shortcuts let you combine multiple rules into a single shorthand, inspired by [Windi CSS's](https://windicss.org/features/shortcuts.html).
## Usage
```ts
shortcuts: {
// shortcuts to multiple utilities
'btn': 'py-2 px-4 font-semibold rounded-lg shadow-md',
'btn-green': 'text-white bg-green-500 hover:bg-green-700',
// single utility alias
'red': 'text-red-100',
}
```
In addition to the plain mapping, UnoCSS also allows you to define dynamic shortcuts.
Similar to [Rules](/config/rules), a dynamic shortcut is the combination of a matcher `RegExp` and a handler function.
```ts
shortcuts: [
// you could still have object style
{
btn: 'py-2 px-4 font-semibold rounded-lg shadow-md',
},
// dynamic shortcuts
[/^btn-(.*)$/, ([, c]) => `bg-${c}-400 text-${c}-100 py-2 px-4 rounded-lg`],
]
```
With this, we could use `btn-green` and `btn-red` to generate the following CSS:
```css
.btn-green {
padding-top: 0.5rem;
padding-bottom: 0.5rem;
padding-left: 1rem;
padding-right: 1rem;
--un-bg-opacity: 1;
background-color: rgb(74 222 128 / var(--un-bg-opacity));
border-radius: 0.5rem;
--un-text-opacity: 1;
color: rgb(220 252 231 / var(--un-text-opacity));
}
.btn-red {
padding-top: 0.5rem;
padding-bottom: 0.5rem;
padding-left: 1rem;
padding-right: 1rem;
--un-bg-opacity: 1;
background-color: rgb(248 113 113 / var(--un-bg-opacity));
border-radius: 0.5rem;
--un-text-opacity: 1;
color: rgb(254 226 226 / var(--un-text-opacity));
}
```
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/config/theme.md
# Path: docs/config/theme.md
---
title: Theme
description: UnoCSS also supports the theming system that you might be familiar with in Tailwind CSS / Windi CSS.
outline: deep
---
# Theme
UnoCSS also supports the theming system that you might be familiar with in Tailwind CSS / Windi CSS. At the user level, you can specify the `theme` property in your config, and it will be deep-merged to the default theme.
## Usage
```ts
theme: {
// ...
colors: {
veryCool: '#0000ff', // class="text-very-cool"
brand: {
primary: 'hsl(var(--hue, 217) 78% 51%)', //class="bg-brand-primary"
DEFAULT: '#942192' //class="bg-brand"
},
},
}
```
::: tip
During the parsing process, `theme` will always exist in `context`.
:::
### Usage in `rules`
To consume the theme in rules:
```ts
rules: [
[/^text-(.*)$/, ([, c], { theme }) => {
if (theme.colors[c])
return { color: theme.colors[c] }
}],
]
```
### Usage in `variants`
To consume the theme in variants:
```ts
variants: [
{
name: 'variant-name',
match(matcher, { theme }) {
// ...
},
},
]
```
### Usage in `shortcuts`
To consume the theme in dynamic shortcuts:
```ts
shortcuts: [
[/^badge-(.*)$/, ([, c], { theme }) => {
if (Object.keys(theme.colors).includes(c))
return `bg-${c}4:10 text-${c}5 rounded`
}],
]
```
## Breakpoints
::: warning
When a custom `breakpoints` object is provided the default will be overridden instead of merging.
:::
With the following example, you will be able to only use the `sm:` and `md:` breakpoint variants:
```ts
theme: {
// ...
breakpoints: {
sm: '320px',
md: '640px',
},
}
```
If you want to inherit the `original` theme breakpoints, you can use the `extendTheme`:
```ts
extendTheme: (theme) => {
return {
...theme,
breakpoints: {
...theme.breakpoints,
sm: '320px',
md: '640px',
},
}
}
```
::: info
`verticalBreakpoints` is same as `breakpoints` but for vertical layout.
:::
In addition we will sort screen points by size (same unit). For screen points in different units, in order to avoid errors, please use unified units in the configuration.
```ts
theme: {
// ...
breakpoints: {
sm: '320px',
// Because uno does not support comparison sorting of different unit sizes, please convert to the same unit.
// md: '40rem',
md: `${40 * 16}px`,
lg: '960px',
},
}
```
## ExtendTheme
`ExtendTheme` allows you to edit the **deeply merged theme** to get the complete theme object.
Custom functions mutate the theme object.
```ts
extendTheme: (theme) => {
theme.colors.veryCool = '#0000ff' // class="text-very-cool"
theme.colors.brand = {
primary: 'hsl(var(--hue, 217) 78% 51%)', // class="bg-brand-primary"
}
}
```
It's also possible to return a new theme object to completely replace the original one.
```ts
extendTheme: (theme) => {
return {
...theme,
colors: {
...theme.colors,
veryCool: '#0000ff', // class="text-very-cool"
brand: {
primary: 'hsl(var(--hue, 217) 78% 51%)', // class="bg-brand-primary"
},
},
}
}
```
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/config/transformers.md
# Path: docs/config/transformers.md
# Transformers
Provides a unified interface to transform source code in order to support conventions.
```ts [my-transformer.ts]
import { SourceCodeTransformer } from 'unocss'
import { createFilter } from 'unplugin-utils'
export default function myTransformers(options: MyOptions = {}): SourceCodeTransformer {
return {
name: 'my-transformer',
enforce: 'pre', // enforce before other transformers
idFilter(id) {
// only transform .tsx and .jsx files
return id.match(/\.[tj]sx$/)
},
async transform(code, id, { uno }) {
// code is a MagicString instance
code.appendRight(0, '/* my transformer */')
},
}
}
```
You can check [official transformers](/presets/#transformers) for more examples.
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/config/variants.md
# Path: docs/config/variants.md
---
title: Variants
description: Variants allow you to apply some variations to your existing rules.
---
# Variants
[Variants](https://windicss.org/utilities/general/variants.html) allow you to apply some variations to your existing rules, like the `hover:` variant from Tailwind CSS.
## Example
```ts
variants: [
// hover:
(matcher) => {
if (!matcher.startsWith('hover:'))
return matcher
return {
// slice `hover:` prefix and passed to the next variants and rules
matcher: matcher.slice(6),
selector: s => `${s}:hover`,
}
},
],
rules: [
[/^m-(\d)$/, ([, d]) => ({ margin: `${d / 4}rem` })],
]
```
- `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.
## Under the hood
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:
```css
.hover\:m-2:hover { margin: 0.5rem; }
```
With this, we could have `m-2` applied only when users hover over the element.
## Going further
The variant system is very powerful and can't be covered fully in this guide, you can check [the default preset's implementation](https://github.com/unocss/unocss/tree/main/packages-presets/preset-mini/src/_variants) to see more advanced usages.
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/index.md
# Path: docs/index.md
---
layout: home
title: "UnoCSS: The instant on-demand Atomic CSS engine"
hero:
image:
src: /logo.svg
alt: UnoCSS
name: "UnoCSS"
text: Instant On-demand Atomic CSS Engine
tagline: Customizable · Powerful · Fast · Joyful
actions:
- theme: brand
text: Getting Started
link: /guide/
- theme: alt
text: Interactive Docs
link: https://unocss.dev/interactive/
target: _blank
- theme: alt
text: Playground
link: https://unocss.dev/play/
target: _blank
- theme: alt
text: Tutorial
link: https://tutorial.unocss.dev/
target: _blank
features:
- icon:
title: Fully Customizable
details: No core utilities, all functionalities are provided via presets.
link: /guide/
linkText: Getting Started
- icon:
title: Instant
details: No parsing, no AST, no scanning. It's 5x faster than Windi CSS or Tailwind CSS JIT.
- icon:
title: Lightweight
details: "Zero deps and browser friendly: ~6kb min+brotli"
- icon:
title: Rich Integrations
details: "First class support of Vite, Webpack, PostCSS, CLI, VS Code, ESLint, etc."
link: /integrations/vite
linkText: "Learn more"
- icon:
title: Shortcuts
details: "Aliasing or grouping utilities, dynamically"
link: /config/shortcuts
linkText: "Configuration and usage"
- icon:
title: Attributify Mode
details: "Group utilities in attributes"
link: /presets/attributify
linkText: "@unocss/preset-attributify"
- icon:
title: Pure CSS Icons
details: "Use any icon as a single class"
link: /presets/icons
linkText: "@unocss/preset-icons"
- icon:
title: Variant Groups
details: "Shorthand for group utils with common prefixes"
link: /transformers/variant-group
linkText: "@unocss/transformer-variant-group"
- icon:
title: CSS Directives
details: "Reuse utils in CSS with @apply directive"
link: /transformers/directives
linkText: "@unocss/transformer-directives"
- icon:
title: Compilation Mode
details: "Synthesizes multiple classes into one at build time"
link: /transformers/compile-class
linkText: "@unocss/transformer-compile-class"
- icon:
title: Inspector
details: "Inspect and debug interactively"
link: /tools/inspector
linkText: "@unocss/inspector"
- icon:
title: CDN Runtime Build
details: "Use UnoCSS with one line of CDN import"
link: /integrations/runtime
linkText: "@unocss/runtime"
---
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/extractors/arbitrary-variants.md
# Path: docs/extractors/arbitrary-variants.md
---
title: Arbitrary Variants Extractor
---
# Arbitrary Variants Extractor
A more complex extractor to support arbitrary variants for utilities.
```html
```
Will be captured with `[&>*]:m-1` and `[&[open]]:p-2` as variants.
This extractor is included in [`@unocss/preset-mini`](/presets/mini) as the default extractor. Normally you don't need to install this package manually.
## Installation
::: code-group
```bash [pnpm]
pnpm add -D @unocss/extractor-arbitrary-variants
```
```bash [yarn]
yarn add -D @unocss/extractor-arbitrary-variants
```
```bash [npm]
npm install -D @unocss/extractor-arbitrary-variants
```
```bash [bun]
bun add -D @unocss/extractor-arbitrary-variants
```
:::
```ts [uno.config.ts]
import extractorArbitrary from '@unocss/extractor-arbitrary-variants'
import { defineConfig } from 'unocss'
export default defineConfig({
extractors: [
extractorArbitrary(),
],
})
```
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/extractors/mdc.md
# Path: docs/extractors/mdc.md
---
title: MDC Extractor
description: MDC extractor for UnoCSS (@unocss/extractor-mdc)
---
# MDC Extractor
Support extracting classes from [MDC (Markdown Components)](https://content.nuxtjs.org/guide/writing/mdc) syntax.
## Installation
::: code-group
```bash [pnpm]
pnpm add -D @unocss/extractor-mdc
```
```bash [yarn]
yarn add -D @unocss/extractor-mdc
```
```bash [npm]
npm install -D @unocss/extractor-mdc
```
```bash [bun]
bun add -D @unocss/extractor-mdc
```
:::
```ts [uno.config.ts]
import extractorMdc from '@unocss/extractor-mdc'
import { defineConfig } from 'unocss'
export default defineConfig({
extractors: [
extractorMdc(),
],
})
```
It will apply the extraction on `.md` `.mdc` and `.markdown` files, to extract inline props usage of classes. For example
```md
# Title{.text-2xl.font-bold}
Hello [World]{.text-blue-500}
{.w-32.h-32}
```
The `text-2xl`, `font-bold`, `text-blue-500`, `w-32`, `h-32` classes will be extracted.
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/extractors/pug.md
# Path: docs/extractors/pug.md
---
title: Pug Extractor
description: Pug extractor for UnoCSS (@unocss/extractor-pug)
---
# Pug Extractor
Support extracting classes from Pug template.
## Installation
::: code-group
```bash [pnpm]
pnpm add -D @unocss/extractor-pug
```
```bash [yarn]
yarn add -D @unocss/extractor-pug
```
```bash [npm]
npm install -D @unocss/extractor-pug
```
```bash [bun]
bun add -D @unocss/extractor-pug
```
:::
```ts [uno.config.ts]
import extractorPug from '@unocss/extractor-pug'
import { defineConfig } from 'unocss'
export default defineConfig({
extractors: [
extractorPug(),
],
})
```
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/extractors/svelte.md
# Path: docs/extractors/svelte.md
---
title: Svelte Extractor
---
# Svelte Extractor
Supports extracting classes from `class:` directive.
```svelte
```
Will be extracted as `text-orange-400` and generates:
```css
.text-orange-400 {
color: #f6993f;
}
```
## Installation
::: code-group
```bash [pnpm]
pnpm add -D @unocss/extractor-svelte
```
```bash [yarn]
yarn add -D @unocss/extractor-svelte
```
```bash [npm]
npm install -D @unocss/extractor-svelte
```
```bash [bun]
bun add -D @unocss/extractor-svelte
```
:::
```ts [uno.config.ts]
import extractorSvelte from '@unocss/extractor-svelte'
import { defineConfig } from 'unocss'
export default defineConfig({
extractors: [
extractorSvelte(),
],
})
```
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/guide/config-file.md
# Path: docs/guide/config-file.md
# Config File
We **highly recommend to use a dedicated `uno.config.ts` file** to configure your UnoCSS, in order to get the best experience with IDEs and other integrations.
A full featured config file looks like this:
```ts twoslash [uno.config.ts]
import {
defineConfig,
presetAttributify,
presetIcons,
presetTypography,
presetWebFonts,
presetWind3,
transformerDirectives,
transformerVariantGroup
} from 'unocss'
export default defineConfig({
shortcuts: [
// ...
],
theme: {
colors: {
// ...
}
},
presets: [
presetWind3(),
presetAttributify(),
presetIcons(),
presetTypography(),
presetWebFonts({
fonts: {
// ...
},
}),
],
transformers: [
transformerDirectives(),
transformerVariantGroup(),
],
})
```
Compared to the inline configuration inside your `vite.config.ts` or other tools configurations, the dedicated config file will work better with [IDEs](/integrations/vscode) and integrations, with other tools like the [ESLint plugin](/integrations/eslint), in addition making HMR work better.
By default, UnoCSS will automatically look for `uno.config.{js,ts,mjs,mts}` or `unocss.config.{js,ts,mjs,mts}` in the root directory of your project. You can also specify the config file manually, for example in Vite:
```ts [vite.config.ts]
import UnoCSS from 'unocss/vite'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
UnoCSS({
configFile: '../my-uno.config.ts',
}),
],
})
```
For the full list of supported configuration options, please refer to the [Configurations reference](/config/).
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/guide/extracting.md
# Path: docs/guide/extracting.md
---
outline: deep
---
# Extracting
UnoCSS works by searching for the utilities usages from your codebase and generate the corresponding CSS on-demand. We call this process **extracting**.
## Content Sources
UnoCSS supports extracting utilities usages from multiple sources:
- [Pipeline](#extracting-from-build-tools-pipeline) - Extract right from your build tools pipeline
- [Filesystem](#extracting-from-filesystem) - Extract from your filesystem by reading and watching files
- [Inline](#extracting-from-inline-text) - Extract from inline plain text
Usages of utilities that comes from different sources will be merged together and generate the final CSS.
### Extracting from Build Tools Pipeline
This is supported in the [Vite](/integrations/vite) and [Webpack](/integrations/webpack) integrations.
UnoCSS will read the content that goes through your build tools pipeline and extract the utilities usages from them. This is the most efficient and accurate way to extract as we only extract the usages that are actually used in your app smartly with no additional file I/O is made during the extraction.
By default, UnoCSS will extract the utilities usage from files in your build pipeline with extension `.jsx`, `.tsx`, `.vue`, `.md`, `.html`, `.svelte`, `.astro`, `.marko` and then generate the appropriate CSS on demand. `.js` and `.ts` files are **NOT included by default**.
To configure them, you can update your `uno.config.ts`:
```ts [uno.config.ts]
export default defineConfig({
content: {
pipeline: {
include: [
// the default
/\.(vue|svelte|[jt]sx|vine.ts|mdx?|astro|elm|php|phtml|marko|html)($|\?)/,
// include js/ts files
'src/**/*.{js,ts}',
],
// exclude files
// exclude: []
},
},
})
```
You can also add `@unocss-include` magic comment, per-file basis, anywhere in the file that you want UnoCSS to scan. If you need to scan `*.js` or `*.ts` files, add them in the configuration to include all js/ts files as scan targets.
```ts
// ./some-utils.js
// since `.js` files are not included by default,
// the following comment tells UnoCSS to force scan this file.
// @unocss-include
export const classes = {
active: 'bg-primary text-white',
inactive: 'bg-gray-200 text-gray-500',
}
```
Similarly, you can also add `@unocss-ignore` to bypass the scanning and transforming for the whole file.
If you want the UnoCSS to skip a block of code without being extracted in any extracting files, you can use `@unocss-skip-start` `@unocss-skip-end` in pairs. Note that it must be used **in pairs** to be effective.
```html
Green Large
Red
```
### Extracting from Filesystem
In cases that you are using integrations that does not have access to the build tools pipeline (for example, the [PostCSS](/integrations/postcss) plugin), or you are integrating with backend frameworks such that the code does not go through the pipeline, you can manually specify the files to be extracted.
```ts [uno.config.ts]
export default defineConfig({
content: {
filesystem: [
'src/**/*.php',
'public/*.html',
],
},
})
```
The files matched will be read directly from the filesystem and watched for changes at dev mode.
### Extracting from Inline Text
Additionally, you can also extract utilities usages from inline text, that you might retrieve from elsewhere.
You may also pass an async function to return the content. But note that the function will only be called once at the build time.
```ts [uno.config.ts]
export default defineConfig({
content: {
inline: [
// plain text
'
Some text
',
// async getter
async () => {
const response = await fetch('https://example.com')
return response.text()
},
],
},
})
```
## Limitations
Since UnoCSS works **at build time**, it means that only statically presented utilities will be generated and shipped to your app. Utilities that are used dynamically or fetched from external resources at runtime might **NOT** be detected or applied.
### Safelist
Sometimes you might want to use dynamic concatenations like:
```html
```
Due the fact that UnoCSS works in build time using static extraction, at the compile time it can't possibility know all the combination of the utilities then. For that, you can configure the `safelist` option.
```ts [uno.config.ts]
safelist: 'p-1 p-2 p-3 p-4'.split(' ')
```
The corresponding CSS will always be generated:
```css
.p-1 { padding: 0.25rem; }
.p-2 { padding: 0.5rem; }
.p-3 { padding: 0.75rem; }
.p-4 { padding: 1rem; }
```
Or more flexible:
```ts [uno.config.ts]
safelist: [
...Array.from({ length: 4 }, (_, i) => `p-${i + 1}`),
]
```
If you are seeking for a true dynamic generation at runtime, you may want to check out the [@unocss/runtime](/integrations/runtime) package.
### Static List Combinations
Another ways to work around the limitation of dynamically constructed utilities is that you can use an object that list all the combinations **statically**. For example, if you want to have this:
```html
```
You can create an object that lists all the combinations (assuming you know any possible values of `color` you want to use)
```ts
// Since they are static, UnoCSS will able to extract them on build time
const classes = {
red: 'text-red border-red',
green: 'text-green border-green',
blue: 'text-blue border-blue',
}
```
And then use it in your template:
```html
```
### Blocklist
Similar to `safelist`, you can also configure `blocklist` to exclude some utilities from being generated. This is useful to exclude some extraction false positives. Different from `safelist`, `blocklist` accepts both string for exact match and regular expression for pattern match.
```ts [uno.config.ts]
blocklist: [
'p-1',
/^p-[2-4]$/,
]
```
This will exclude `p-1` and `p-2`, `p-3`, `p-4` from being generated.
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/guide/index.md
# Path: docs/guide/index.md
---
title: Guide
description: Getting started with UnoCSS
---
# What is UnoCSS?
UnoCSS is the instant atomic CSS engine, that is designed to be flexible and extensible. The core is un-opinionated and all the CSS utilities are provided via presets.
For example, you could define your custom CSS utilities, by providing rules in your local [config file](/guide/config-file).
```ts [uno.config.ts]
import { defineConfig } from 'unocss'
export default defineConfig({
rules: [
['m-1', { margin: '1px' }],
],
})
```
This will add a new CSS utility `m-1` to your project. Since UnoCSS is on-demand, it won't do anything until you use it in your codebase. So say we have a component like this:
```html
Hello
```
`m-1` will be detected and the following CSS will be generated:
```css
.m-1 { margin: 1px; }
```
To make it more flexible, you can make your rule dynamic by changing the first argument on the rule (we call it matcher) to a `RegExp`, and the body to a function, for example:
```diff [uno.config.ts]
export default defineConfig({
rules: [
- ['m-1', { margin: '1px' }],
+ [/^m-([\.\d]+)$/, ([_, num]) => ({ margin: `${num}px` })],
],
})
```
By doing this, now you can have arbitrary margin utilities, like `m-1`, `m-100` or `m-52.43`. And again, UnoCSS only generates them whenever you use them.
```html
```
:::
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/integrations/svelte-scoped.md
# Path: docs/integrations/svelte-scoped.md
---
title: UnoCSS Svelte Scoped
description: Svelte Scoped Vite Plugin and Svelte Preprocessor for UnoCSS.
outline: deep
---
# Svelte Scoped
Place generated CSS for each Svelte component's utility styles directly into the Svelte component's `
```
## When to use
| Use Case | | Description | Package to Use |
| ----------------- | --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| Smaller apps | :x: | Having 1 global CSS file is more convenient. Use the regular Vite plugin for [Svelte](/integrations/vite#svelte)/[SvelteKit](/integrations/vite#sveltekit). | [unocss/vite](/integrations/vite#svelte) |
| Larger apps | ✅ | Svelte Scoped can help you avoid an ever-growing global CSS file. | [@unocss/svelte-scoped/vite](#vite-plugin) |
| Component library | ✅ | Generated styles are placed directly in built components without the need to use UnoCSS in a consuming app's build pipeline. | [@unocss/svelte-scoped/preprocess](#svelte-preprocessor) |
## How it works
A regular UnoCSS/Tailwind CSS setup places utility styles in a global CSS file with proper ordering. In contrast, Svelte Scoped distributes your styles across many arbitrarily ordered Svelte component CSS files. However, it must keep the utility styles global to allow them to be context aware as needed for things like right-to-left and other [use cases](#context-aware) listed below. This presents a challenge that is solved by using Svelte's `:global()` wrapper to opt out of the default Svelte CSS hashing method and instead use a hash based on filename + class name(s) to compile unique class names that can be made global without style conflicts.
## Usage
Because Svelte Scoped rewrites your utility class names, you are limited in where you can write them:
| Supported Syntax | Example |
| ------------------------- | ------------------------------------------------------------------------------------------- |
| Class attribute | `` |
| Class directive | `` |
| Class directive shorthand | `` |
| Class prop | `` |
| `clsx` like | `` |
Svelte Scoped is designed to be a drop-in replacement for a project that uses utility styles. As such, expressions found within class attributes are also supported (e.g. ``) but we recommend you use the `clsx` syntax moving forward. Note also that if you've used class names in other ways like placing them in a `
# Vite Plugin
The Vite plugin ships with the `unocss` package.
## Installation
::: code-group
```bash [pnpm]
pnpm add -D unocss
```
```bash [yarn]
yarn add -D unocss
```
```bash [npm]
npm install -D unocss
```
```bash [bun]
bun add -D unocss
```
:::
Install the plugin:
```ts [vite.config.ts]
import UnoCSS from 'unocss/vite'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
UnoCSS(),
],
})
```
Create a `uno.config.ts` file:
```ts [uno.config.ts]
import { defineConfig } from 'unocss'
export default defineConfig({
// ...UnoCSS options
})
```
Add `virtual:uno.css` to your main entry:
```ts [main.ts]
import 'virtual:uno.css'
```
## Modes
The Vite plugin comes with a set of modes that enable different behaviors.
### `global` (default)
This is the default mode for the plugin: in this mode you need to add the import of `uno.css` on your entry point.
This mode enables a set of Vite plugins for `build` and for `dev` with `HMR` support.
The generated `css` will be a global stylesheet injected on the `index.html`.
### `vue-scoped`
This mode will inject generated CSS to Vue SFCs `
...
`
```
If you're using [Lit](https://lit.dev/):
```ts
@customElement('my-element')
export class MyElement extends LitElement {
static styles = css`
:host {...}
@unocss-placeholder
`
// ...
}
```
You have a `Web Components` example project on [examples/vite-lit](https://github.com/unocss/unocss/tree/main/examples/vite-lit) directory.
#### `::part` built-in support
You can use `::part` since the plugin supports it via `shortcuts` and using `part-[]:` rule from `preset-mini`, for example using it with simple rules like `part-[]:bg-green-500` or using some `shortcut`: check `src/my-element.ts` on linked example project below.
The `part-[]:` will work only with this plugin using the `shadow-dom` mode.
The plugin uses `nth-of-type` to avoid collisions with multiple parts in the same web component and for the same parts on distinct web components, you don't need to worry about it, the plugin will take care for you.
```ts [vite.config.ts]
import UnoCSS from 'unocss/vite'
export default {
plugins: [
UnoCSS({
mode: 'shadow-dom',
shortcuts: [
{ 'cool-blue': 'bg-blue-500 text-white' },
{ 'cool-green': 'bg-green-500 text-black' },
],
/* more options */
}),
],
}
```
then in your web components:
```ts
// my-container-wc.ts
const template = document.createElement('template')
template.innerHTML = `
...
`
```
```ts
// my-wc-with-parts.ts
const template = document.createElement('template')
template.innerHTML = `
## Features
Inspired by [Windi CSS](http://windicss.org/), [Tailwind CSS](https://tailwindcss.com/), and [Twind](https://github.com/tw-in-js/twind), but:
- [Fully customizable](https://unocss.dev/config/) - 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](https://unocss.dev/config/shortcuts) - aliasing utilities, dynamically.
- [Attributify mode](https://unocss.dev/presets/attributify/) - group utilities in attributes.
- [Pure CSS Icons](https://unocss.dev/presets/icons/) - use any icon as a single class.
- [Variant Groups](https://unocss.dev/transformers/variant-group) - shorthand for group utils with common prefixes.
- [CSS Directives](https://unocss.dev/transformers/directives) - reuse utils in CSS with `@apply` directive.
- [Compilation mode](https://unocss.dev/transformers/compile-class/) - synthesizes multiple classes into one at build time.
- [Inspector](https://unocss.dev/tools/inspector) - inspect and debug interactively.
- [CSS-in-JS Runtime build](https://unocss.dev/integrations/runtime) - use UnoCSS with one line of CDN import.
- [VS Code extension](https://marketplace.visualstudio.com/items?itemName=antfu.unocss)
- Code-splitting for CSS - ships minimal CSS for MPA.
## Documentation
Read the [documentation](https://unocss.dev/) for more details.
## Installation
- [Vite](https://unocss.dev/integrations/vite)
- [Nuxt](https://unocss.dev/integrations/nuxt)
- [Astro](https://unocss.dev/integrations/astro)
- [Webpack](https://unocss.dev/integrations/webpack)
- [CDN Runtime](https://unocss.dev/integrations/runtime)
- [CLI](https://unocss.dev/integrations/cli)
- [VS Code extension](https://unocss.dev/integrations/vscode)
- [ESLint Config](https://unocss.dev/integrations/eslint)
- [PostCSS](https://unocss.dev/integrations/postcss)
## Acknowledgement
UnoCSS is made possible thanks to the inspirations from the following projects:
> in alphabetical order
- [ACSS](https://acss-io.github.io/atomizer/)
- [Bootstrap Utilities](https://getbootstrap.com/docs/5.1/utilities/flex/)
- [Chakra UI Style Props](https://chakra-ui.com/docs/features/style-props)
- [Semantic UI](https://semantic-ui.com/)
- [Tachyons](https://tachyons.io/)
- [Tailwind CSS](https://tailwindcss.com/)
- [Twind](https://github.com/tw-in-js/twind)
- [Windi CSS](http://windicss.org/)
## Sponsors
` which will make the generated CSS from UnoCSS fail to match the attributes. To solve this, you might want to try [`transformer-attributify-jsx`](/transformers/attributify-jsx) along with this preset.
:::
## Properties conflicts
If the name of the attributes mode ever conflicts with the elements' or components' properties, you can add `un-` prefix to be specific to UnoCSS's attributify mode.
For example:
```html
This conflicts with links' `text` propText color to red
```
Prefix is optional by default, if you want to enforce the usage of prefix, set
```ts
presetAttributify({
prefix: 'un-',
prefixedOnly: true, // <--
})
```
You can also disable the scanning for certain attributes by:
```ts
presetAttributify({
ignoreAttributes: [
'text'
// ...
]
})
```
## TypeScript support (JSX/TSX)
Create `shims.d.ts` with the following content:
> By default, the type includes common attributes from `@unocss/preset-wind3`. If you need custom attributes, refer to the [type source](https://github.com/unocss/unocss/blob/main/packages-presets/preset-attributify/src/jsx.ts) to implement your own type.
### Vue
Since Volar 0.36, [it's now strict to unknown attributes](https://github.com/johnsoncodehk/volar/issues/1077#issuecomment-1145361472). To opt-out, you can add the following file to your project:
```ts [html.d.ts]
declare module '@vue/runtime-dom' {
interface HTMLAttributes {
[key: string]: any
}
}
declare module '@vue/runtime-core' {
interface AllowedComponentProps {
[key: string]: any
}
}
export {}
```
### React
```ts
import type { AttributifyAttributes } from '@unocss/preset-attributify'
declare module 'react' {
interface HTMLAttributes extends AttributifyAttributes {}
}
```
### Vue 3
```ts
import type { AttributifyAttributes } from '@unocss/preset-attributify'
declare module '@vue/runtime-dom' {
interface HTMLAttributes extends AttributifyAttributes {}
}
```
### SolidJS
```ts
import type { AttributifyAttributes } from '@unocss/preset-attributify'
declare module 'solid-js' {
namespace JSX {
interface HTMLAttributes extends AttributifyAttributes {}
}
}
```
### Svelte & SvelteKit
```ts
declare namespace svelteHTML {
import type { AttributifyAttributes } from '@unocss/preset-attributify'
type HTMLAttributes = AttributifyAttributes
}
```
### Astro
```ts
import type { AttributifyAttributes } from '@unocss/preset-attributify'
declare global {
namespace astroHTML.JSX {
interface HTMLAttributes extends AttributifyAttributes { }
}
}
```
### Preact
```ts
import type { AttributifyAttributes } from '@unocss/preset-attributify'
declare module 'preact' {
namespace JSX {
interface HTMLAttributes extends AttributifyAttributes {}
}
}
```
### Marko
```ts
import type { AttributifyAttributes } from '@unocss/preset-attributify'
declare global {
namespace Marko {
interface HTMLAttributes extends AttributifyAttributes {}
}
}
```
### Attributify with Prefix
```ts
import type { AttributifyNames } from '@unocss/preset-attributify'
type Prefix = 'uno:' // change it to your prefix
interface HTMLAttributes extends Partial, string>> {}
```
## Options
### strict
- **type:** `boolean`
- **default:** `false`
Only generate CSS for attributify or class.
### prefix
- **type:** `string`
- **default:** `'un-'`
The prefix for attributify mode.
### prefixedOnly
- **type:** `boolean`
- **default:** `false`
Only match for prefixed attributes.
### nonValuedAttribute
- **type:** `boolean`
- **default:** `true`
Support matching non-valued attributes.
### ignoreAttributes
- **type:** `string[]`
A list of attributes to be ignored from extracting.
### trueToNonValued
- **type:** `boolean`
- **default:** `false`
Non-valued attributes will also match if the actual value represented in DOM is `true`. This option exists for supporting frameworks that encodes non-valued attributes as `true`. Enabling this option will break rules that ends with `true`.
## Credits
Initial idea by [@Tahul](https://github.com/Tahul) and [@antfu](https://github.com/antfu). Prior [implementation in Windi CSS](https://windicss.org/posts/v30.html#attributify-mode) by [@voorjaar](https://github.com/voorjaar).
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/presets/community.md
# Path: docs/presets/community.md
# Community
We warmly welcome everyone to join and help build the [UnoCSS community](https://github.com/unocss-community). You can use and share UnoCSS-related resources in [Awesome UnoCSS](https://github.com/unocss-community/awesome-unocss).
---
# UnoCSS Documentation
# Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/presets/icons.md
# Path: docs/presets/icons.md
---
title: Icons preset
description: Use any icon with Pure CSS for UnoCSS (@unocss/preset-icons).
outline: deep
---
# Icons preset
Use any icon with Pure CSS for UnoCSS.
[Source Code](https://github.com/unocss/unocss/tree/main/packages-presets/preset-icons)
::: tip
Recommended reading: [Icons in Pure CSS](https://antfu.me/posts/icons-in-pure-css)
:::
Follow the following conventions to use the icons
- `-`
- `:`
For example:
```html
```
Hover it
Check [all available icons](https://icones.js.org/).
## Install
::: code-group
```bash [pnpm]
pnpm add -D @unocss/preset-icons @iconify-json/[the-collection-you-want]
```
```bash [yarn]
yarn add -D @unocss/preset-icons @iconify-json/[the-collection-you-want]
```
```bash [npm]
npm install -D @unocss/preset-icons @iconify-json/[the-collection-you-want]
```
```bash [bun]
bun add -D @unocss/preset-icons @iconify-json/[the-collection-you-want]
```
:::
We use [Iconify](https://iconify.design) as our data source of icons. You need to install the corresponding icon-set in `devDependencies` by following the `@iconify-json/*` pattern. For example, `@iconify-json/mdi` for [Material Design Icons](https://materialdesignicons.com/), `@iconify-json/tabler` for [Tabler](https://tabler-icons.io/). You can refer to [Icônes](https://icones.js.org/) or [Iconify](https://icon-sets.iconify.design/) for all the collections available.
```ts [uno.config.ts]
import presetIcons from '@unocss/preset-icons'
import { defineConfig } from 'unocss'
export default defineConfig({
presets: [
presetIcons({ /* options */ }),
// ...other presets
],
})
```
::: tip
This preset is included in the `unocss` package, you can also import it from there:
```ts
import { presetIcons } from 'unocss'
```
:::
::: info
You can also use this preset alone as a complement to your existing UI frameworks to have pure CSS icons!
:::
If you prefer to install all the icon sets available on Iconify at once (~130MB):
::: code-group
```bash [pnpm]
pnpm add -D @iconify/json
```
```bash [yarn]
yarn add -D @iconify/json
```
```bash [npm]
npm install -D @iconify/json
```
```bash [bun]
bun add -D @iconify/json
```
:::
### Extra Properties
You can provide the extra CSS properties to control the default behavior of the icons. The following is an example of making icons inlined by default:
```ts
presetIcons({
extraProperties: {
'display': 'inline-block',
'vertical-align': 'middle',
// ...
},
})
```
## Modes Overriding
By default, this preset will choose the rendering modes automatically for each icon based on the icons' characteristics. You can read more in this [blog post](https://antfu.me/posts/icons-in-pure-css). In some cases, you may want to explicitly set the rendering modes for each icon.
- `?bg` for `background-img` - renders the icon as a background image
- `?mask` for `mask` - renders the icon as a mask image
For example, `vscode-icons:file-type-light-pnpm`, an icon with colors (the `svg` doesn't contain `currentColor`) that will be rendered as a background image. Use `vscode-icons:file-type-light-pnpm?mask` to render it as a mask image and bypass it's colors.
```html
```
## Configuring collections and icons resolvers
You can provide collections via `@iconify-json/[the-collection-you-want]`, `@iconify/json` or using your custom ones using `collections` option on your `UnoCSS` configuration.
### Browser
To load `iconify` collections you should use `@iconify-json/[the-collection-you-want]` and not `@iconify/json` since the `json` file is huge.
#### Bundler
When using bundlers, you can provide the collections using `dynamic imports` so they will be bundler as async chunk and loaded on demand.
```ts
import presetIcons from '@unocss/preset-icons/browser'
export default defineConfig({
presets: [
presetIcons({
collections: {
carbon: () => import('@iconify-json/carbon/icons.json').then(i => i.default),
mdi: () => import('@iconify-json/mdi/icons.json').then(i => i.default),
logos: () => import('@iconify-json/logos/icons.json').then(i => i.default),
}
})
]
})
```
#### CDN
Or if you prefer to fetch them from CDN, you can specify the `cdn` option since `v0.32.10`. We recommend [esm.sh](https://esm.sh/) as the CDN provider.
```ts
presetIcons({
cdn: 'https://esm.sh/'
})
```
#### Customization
You can also provide your own custom collections using [CustomIconLoader](https://github.com/iconify/iconify/blob/master/packages/utils/src/loader/types.ts#L17) or [InlineCollection](https://github.com/iconify/iconify/blob/master/packages/utils/src/loader/types.ts#L86), for example using `InlineCollection`:
```ts
presetIcons({
collections: {
custom: {
circle: '',
/* ... */
},
carbon: () => import('@iconify-json/carbon/icons.json').then(i => i.default as any),
/* ... */
}
})
```
And then, you can use it on your html: ``
### Node.js
In `Node.js` the preset will search for the installed iconify dataset automatically, so you don't need to register the `iconify` collections.
You can also provide your own custom collections using also [CustomIconLoader](https://github.com/iconify/iconify/blob/master/packages/utils/src/loader/types.ts#L24) or [InlineCollection](https://github.com/iconify/iconify/blob/master/packages/utils/src/loader/types.ts#L100).
#### FileSystemIconLoader
Additionally, you can also use [FileSystemIconLoader](https://github.com/iconify/iconify/blob/master/packages/utils/src/loader/node-loaders.ts#L9) to load your custom icons from your file system. You will need to install `@iconify/utils` package as `dev dependency`.
```ts [unocss.config.ts]
import fs from 'node:fs/promises'
// loader helpers
import { FileSystemIconLoader } from '@iconify/utils/lib/loader/node-loaders'
import { defineConfig, presetIcons } from 'unocss'
export default defineConfig({
presets: [
presetIcons({
collections: {
// key as the collection name
'my-icons': {
account: '',
// load your custom icon lazily
settings: () => fs.readFile('./path/to/my-icon.svg', 'utf-8'),
/* ... */
},
'my-other-icons': async (iconName) => {
// your custom loader here. Do whatever you want.
// for example, fetch from a remote server:
return await fetch(`https://example.com/icons/${iconName}.svg`).then(res => res.text())
},
// a helper to load icons from the file system
// files under `./assets/icons` with `.svg` extension will be loaded as it's file name
// you can also provide a transform callback to change each icon (optional)
'my-yet-other-icons': FileSystemIconLoader(
'./assets/icons',
svg => svg.replace(/#fff/, 'currentColor')
)
}
})
]
})
```
#### ExternalPackageIconLoader
From `@iconify/utils v2.1.20` you can use other packages to load icons from others authors using the new [createExternalPackageIconLoader](https://github.com/iconify/iconify/blob/main/packages/utils/src/loader/external-pkg.ts#L13) helper.
::: warning WARNING
External packages must include `icons.json` file with the `icons` data in `IconifyJSON` format, which can be exported with Iconify Tools. Check [Exporting icon set as JSON package](https://iconify.design/docs/libraries/tools/export/json-package.html) for more details.
:::
For example, you can use `an-awesome-collection` or `@my-awesome-collections/some-collection` to load your custom or third party icons:
```ts [unocss.config.ts]
import { createExternalPackageIconLoader } from '@iconify/utils/lib/loader/external-pkg'
import { defineConfig, presetIcons } from 'unocss'
export default defineConfig({
presets: [
presetIcons({
collections: createExternalPackageIconLoader('an-awesome-collection')
})
]
})
```
You can also combine it with other custom icon loaders, for example:
```ts [unocss.config.ts]
import { createExternalPackageIconLoader } from '@iconify/utils/lib/loader/external-pkg'
import { defineConfig, presetIcons } from 'unocss'
import { FileSystemIconLoader } from 'unplugin-icons/loaders'
export default defineConfig({
presets: [
presetIcons({
collections: {
...createExternalPackageIconLoader('other-awesome-collection'),
...createExternalPackageIconLoader('@my-awesome-collections/some-collection'),
...createExternalPackageIconLoader('@my-awesome-collections/some-other-collection'),
'my-yet-other-icons': FileSystemIconLoader(
'./assets/icons',
svg => svg.replace(/^