# 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} ![image](/image.png){.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
Hello
World
``` ```css .m-1 { margin: 1px; } .m-7.5 { margin: 7.5px; } ``` ## Presets Once you made a few rules, you can extract them into a preset, and share it with others. For example, you can create a preset for your company's design system, and share it with your team. ```ts [my-preset.ts] import { Preset } from 'unocss' export const myPreset: Preset = { name: 'my-preset', rules: [ [/^m-([.\d]+)$/, ([_, num]) => ({ margin: `${num}px` })], [/^p-([.\d]+)$/, ([_, num]) => ({ padding: `${num}px` })], ], variants: [/* ... */], shortcuts: [/* ... */], // ... } ``` ```ts [uno.config.ts] import { defineConfig } from 'unocss' import { myPreset } from './my-preset' export default defineConfig({ presets: [ myPreset, // your own preset ], }) ``` So similarly, we provided a few [official presets](/presets/) for you to start using right away, and you can also find many interesting [community presets](/presets/community). ## Play You can try UnoCSS in your browser, in the Playground. Or look up utilities from the default presets in the Interactive Docs. ## Integrations UnoCSS comes with integrations for various frameworks / tools: ## Examples Source code for all the examples can be found in the [/examples](https://github.com/unocss/unocss/tree/main/examples) directory. --- # UnoCSS Documentation # Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/guide/packages.md # Path: docs/guide/packages.md --- title: Packages description: "UnoCSS Packages: available packages and what's included and enabled in unocss." outline: deep --- # Packages UnoCSS is a monorepo that contains multiple packages. This page lists all the packages and what's included in `unocss` package: | Package | Description | Included in `unocss` | Enabled | | -------------------------------------------------------------------- | ------------------------------------------------- | -------------------- | ------- | | [@unocss/core](/tools/core) | The core library without preset | ✅ | - | | [@unocss/cli](/integrations/cli) | Command line interface for UnoCSS | ✅ | - | | [@unocss/preset-mini](/presets/mini) | The minimal but essential rules and variants | ✅ | ✅ | | [@unocss/preset-wind3](/presets/wind3) | Tailwind CSS / Windi CSS compact preset | ✅ | ✅ | | [@unocss/preset-wind4](/presets/wind4) | Tailwind4 CSS compact preset | ✅ | ✅ | | [@unocss/preset-attributify](/presets/attributify) | Enables Attributify Mode for other rules | ✅ | No | | [@unocss/preset-tagify](/presets/tagify) | Enables Tagify Mode for other rules | ✅ | No | | [@unocss/preset-icons](/presets/icons) | Pure CSS Icons solution powered by Iconify | ✅ | No | | [@unocss/preset-web-fonts](/presets/web-fonts) | Web fonts (Google Fonts, etc.) support | ✅ | No | | [@unocss/preset-typography](/presets/typography) | The typography preset | ✅ | No | | [@unocss/preset-rem-to-px](/presets/rem-to-px) | Coverts rem to px for utils | No | No | | [@unocss/preset-legacy-compat](/presets/legacy-compat) | Collections of legacy compatibility utilities | No | No | | [@unocss/transformer-variant-group](/transformers/variant-group) | Transformer for Windi CSS's variant group feature | ✅ | No | | [@unocss/transformer-directives](/transformers/directives) | Transformer for CSS directives like `@apply` | ✅ | No | | [@unocss/transformer-compile-class](/transformers/compile-class) | Compile group of classes into one class | ✅ | No | | [@unocss/transformer-attributify-jsx](/transformers/attributify-jsx) | Support valueless attributify in JSX/TSX | ✅ | No | | [@unocss/extractor-pug](/extractors/pug) | Extractor for Pug | No | - | | [@unocss/extractor-svelte](/extractors/svelte) | Extractor for Svelte | No | - | | [@unocss/autocomplete](/tools/autocomplete) | Utils for autocomplete | No | - | | [@unocss/config](/guide/config-file) | Configuration file loader | ✅ | - | | [@unocss/reset](/guide/style-reset) | Collection of common CSS resets | ✅ | No | | [@unocss/vite](/integrations/vite) | The Vite plugins | ✅ | - | | [@unocss/inspector](/tools/inspector) | The inspector UI for UnoCSS | ✅ | - | | [@unocss/astro](/integrations/astro) | The Astro integration | ✅ | - | | [@unocss/webpack](/integrations/webpack) | The Webpack plugin | No | - | | [@unocss/nuxt](/integrations/nuxt) | The Nuxt Module | No | - | | [@unocss/svelte-scoped](/integrations/svelte-scoped) | Svelte Scoped Vite plugin + Preprocessor | No | - | | [@unocss/next](/integrations/next) | The Next.js plugin | No | - | | [@unocss/runtime](/integrations/runtime) | CSS-in-JS Runtime for UnoCSS | No | - | | [@unocss/eslint-plugin](/integrations/eslint) | ESLint plugin | No | - | | [@unocss/eslint-config](/integrations/eslint) | ESLint config | No | - | | [@unocss/postcss](/integrations/postcss) | The PostCSS plugin | No | - | | [VS Code Extension](/integrations/vscode) | UnoCSS for VS Code | - | - | --- # UnoCSS Documentation # Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/guide/presets.md # Path: docs/guide/presets.md --- title: Presets description: Presets are the heart of UnoCSS. They let you make your own custom framework in minutes. outline: deep --- # Presets Presets are the heart of UnoCSS. They let you make your own custom framework in minutes. ### Using presets To set presets to your project: ```ts twoslash [uno.config.ts] import { defineConfig, presetAttributify, presetWind3 } from 'unocss' export default defineConfig({ presets: [ presetAttributify({ /* preset options */}), presetWind3(), // ...custom presets ], }) ``` 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: ```ts twoslash [uno.config.ts] import { defineConfig } from 'unocss' export default defineConfig({ presets: [], // disable default preset rules: [ // your custom rules ], }) ``` You can check [official presets](/presets/) and [community presets](/presets/community) for more. ### Creating presets To see how you can create your own custom preset, see [Config: presets](/config/presets). --- # UnoCSS Documentation # Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/guide/style-reset.md # Path: docs/guide/style-reset.md --- title: Style Reset description: UnoCSS does not provide style resetting or preflight by default for maximum flexibility and does not populate your global CSS. outline: deep --- # Browser Style Reset UnoCSS does not provide style resetting or preflight by default so not to populate your global CSS and also for maximum flexibility. 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](https://github.com/csstools/normalize.css). We also provide a small collection for you to grab them quickly: ## Installation ::: code-group ```bash [pnpm] pnpm add @unocss/reset ``` ```bash [yarn] yarn add @unocss/reset ``` ```bash [npm] npm install @unocss/reset ``` ```bash [bun] bun add @unocss/reset ``` ::: ## Usage You can add one of the following reset stylesheets to your `main.js`. ### Normalize.css Source: https://github.com/csstools/normalize.css ```ts import '@unocss/reset/normalize.css' ``` ### sanitize.css Source: https://github.com/csstools/sanitize.css ```ts import '@unocss/reset/sanitize/sanitize.css' import '@unocss/reset/sanitize/assets.css' ``` ### Eric Meyer Source: https://meyerweb.com/eric/tools/css/reset/index.html ```ts import '@unocss/reset/eric-meyer.css' ``` ### Tailwind Based on older [Preflight](https://github.com/tailwindlabs/tailwindcss/blob/v3.4.18/src/css/preflight.css), with select recent changes ```ts import '@unocss/reset/tailwind.css' ``` ### Tailwind v4 Based on [Preflight](https://github.com/tailwindlabs/tailwindcss/blob/main/packages/tailwindcss/preflight.css) ```ts import '@unocss/reset/tailwind-v4.css' ``` ### Tailwind compat ```ts import '@unocss/reset/tailwind-compat.css' ``` This reset is based on [Tailwind reset](#tailwind), minus the background color override for buttons to avoid conflicts with UI frameworks. See [linked issue](https://github.com/unocss/unocss/issues/2127). ::: code-group ```css [Before] button, [type='button'], [type='reset'], [type='submit'] { -webkit-appearance: button; /* 1 */ background-color: transparent; /* 2 */ background-image: none; /* 2 */ } ``` ```css [After] button, [type='button'], [type='reset'], [type='submit'] { -webkit-appearance: button; /* 1 */ /*background-color: transparent; !* 2 *!*/ background-image: none; /* 2 */ } ``` ::: --- # UnoCSS Documentation # Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/guide/why.md # Path: docs/guide/why.md --- outline: deep --- # Why UnoCSS? ## Motivations We recommend you to read the blog post [Reimagine Atomic CSS](https://antfu.me/posts/reimagine-atomic-css) written by the creator of UnoCSS, [Anthony Fu](https://antfu.me/), to get a better understanding of the motivation behind UnoCSS. ## How is UnoCSS Different from X? ### Windi CSS UnoCSS was started by one of the [Windi CSS](https://windicss.org/)'s team members, with a lot of inspiration taken from the work we did in Windi CSS. While Windi CSS is no longer actively maintained (as of March 2023), you may consider UnoCSS as a _"spiritual successor"_ of Windi CSS. UnoCSS inherits Windi CSS's on-demand nature, [attributify mode](/presets/attributify), [shortcuts](/config/shortcuts), [variant groups](/transformers/variant-group), [compilation mode](/transformers/compile-class) and a lot more. On top of that, UnoCSS is built from the ground up with the maximum extensibility and performance in mind, making us able to introduce new features like [pure CSS icons](/presets/icons), [valueless attributify](/presets/attributify#valueless-attributify), [tagify](/presets/tagify), [web fonts](/presets/web-fonts), etc. Most importantly, UnoCSS is extracted as an atomic CSS engine, where all the features are optional, and making it easy to create your own conventions, own design system, and own presets - with the combinations of the features you want. ### Tailwind CSS Both Windi CSS and UnoCSS took a lot of inspiration from [Tailwind CSS](https://tailwindcss.com/). Since UnoCSS is built from the ground up, we are able to have a great overview of how atomic CSS has been designed with prior arts and abstracted into an elegant and powerful API. With quite different design goals, it's not really an apples-to-apples comparison with Tailwind CSS. But we will try to list a few differences. Tailwind CSS is a PostCSS plugin, while UnoCSS is an isomorphic engine with a collection of first-class integrations with build tools (including a [PostCSS plugin](/integrations/postcss)). This means UnoCSS can be much more flexible to be used in different places (for example, [CDN Runtime](/integrations/runtime), which generates CSS on the fly) and have deep integrations with build tools to provide better HMR, performance, and developer experience (for example, the [Inspector](/tools/inspector)). Technical trade-offs aside, UnoCSS is also designed to be fully extensible and customizable, while Tailwind CSS is more opinionated. Building a custom design system (or design tokens) on top of Tailwind CSS can be hard, and you can't really move away from the Tailwind CSS's conventions. With UnoCSS, you can build pretty much anything you want with full control. For example, we implemented the whole Tailwind CSS compatible utilities within [a single preset](/presets/wind3), and there are a lot of [awesome community presets](/presets/community) implemented with other interesting philosophies. Thanks to the flexibility UnoCSS provides, we are able to experiment with a lot of innovative features on top of it, for example: - [Pure CSS icons](/presets/icons) - [Attributify Mode](/presets/attributify) - [Variant Groups](/transformers/variant-group) - [Shortcuts](/config/shortcuts) - [Tagify](/presets/tagify) - [Web fonts](/presets/web-fonts) - [CDN Runtime](/integrations/runtime) - [Inspector](/tools/inspector) Due to the differing design goals over Tailwind CSS, UnoCSS does not support Tailwind CSS's plugin system or configurations, meaning it might make it harder to migrate from a heavily customized Tailwind CSS project. This is the intended decision to make UnoCSS high-performant and extensible, and we believe the trade-off is worth it. --- # UnoCSS Documentation # Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/integrations/astro.md # Path: docs/integrations/astro.md --- title: UnoCSS Astro Integration description: The UnoCSS integration for Astro (@unocss/astro). --- # Astro Integration The UnoCSS integration for [Astro](https://astro.build/): `@unocss/astro`. Check the [example](https://github.com/unocss/unocss/tree/main/examples/astro). ## 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 ``` ::: ```ts [astro.config.ts] import { defineConfig } from 'astro/config' import UnoCSS from 'unocss/astro' export default defineConfig({ integrations: [ UnoCSS(), ], }) ``` Create a `uno.config.ts` file: ```ts [uno.config.ts] import { defineConfig } from 'unocss' export default defineConfig({ // ...UnoCSS options }) ``` ### Style Reset By default, [browser style reset](/guide/style-reset) will not be injected. To enable it, install the `@unocss/reset` package: ::: code-group ```bash [pnpm] pnpm add -D @unocss/reset ``` ```bash [yarn] yarn add -D @unocss/reset ``` ```bash [npm] npm install -D @unocss/reset ``` ```bash [bun] bun add -D @unocss/reset ``` ::: And update your `astro.config.ts`: ```ts [astro.config.ts] import { defineConfig } from 'astro/config' import UnoCSS from 'unocss/astro' export default defineConfig({ integrations: [ UnoCSS({ injectReset: true // or a path to the reset file }), ], }) ``` ### Usage without presets This plugin does not come with any default presets. ::: code-group ```bash [pnpm] pnpm add -D @unocss/astro ``` ```bash [yarn] yarn add -D @unocss/astro ``` ```bash [npm] npm install -D @unocss/astro ``` ```bash [bun] bun add -D @unocss/astro ``` ::: ```ts [astro.config.mjs] import UnoCSS from '@unocss/astro' export default { integrations: [ UnoCSS(), ], } ``` For more details, please refer to the [Vite plugin](/integrations/vite). ::: info If you are building a meta framework on top of UnoCSS, see [this file](https://github.com/unocss/unocss/blob/main/packages-presets/unocss/src/astro.ts) for an example on how to bind the default presets. ::: ## Notes [`client:only`](https://docs.astro.build/en/reference/directives-reference/#clientonly) components must be placed in [`components`](https://docs.astro.build/en/core-concepts/project-structure/#srccomponents) folder or added to UnoCSS's `content` config in order to be processed. --- # UnoCSS Documentation # Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/integrations/cli.md # Path: docs/integrations/cli.md --- title: UnoCSS CLI description: The CLI for UnoCSS (@unocss/cli). --- # CLI The command line interface for UnoCSS: `@unocss/cli`. - 🍱 Suited for traditional backends like Laravel or Kirby - 👀 [Watch mode](#development) included - 🔌 Supports custom configurations via [`uno.config.ts`](#configurations) ## Installation This package is shipped with the `unocss` package: ::: 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 ``` ::: You can also install the standalone package: ::: code-group ```bash [pnpm] pnpm add -D @unocss/cli ``` ```bash [yarn] yarn add -D @unocss/cli ``` ```bash [npm] npm install -D @unocss/cli ``` ```bash [bun] bun add -D @unocss/cli ``` ::: ::: info If you are not able to find the binary (e.g. with `pnpm` and only `unocss` is installed), you'll need to explicit install `@unocss/cli` standalone package. ::: ## Usage You can also pass multiple glob patterns to `@unocss/cli`: ```bash unocss "site/snippets/**/*.php" "site/templates/**/*.php" ``` Example package configuration: ::: info Make sure to add escaped quotes to your npm script glob patterns. ::: ```json [package.json] { "scripts": { "dev": "unocss \"site/{snippets,templates}/**/*.php\" --watch", "build": "unocss \"site/{snippets,templates}/**/*.php\"" }, "devDependencies": { "@unocss/cli": "latest" } } ``` ### Development Add the `--watch` (or `-w`) flag to enable watching for file changes: ```bash unocss "site/{snippets,templates}/**/*.php" --watch ``` ### Production ```bash unocss "site/{snippets,templates}/**/*.php" ``` The final `uno.css` will be generated to the current directory by default. ## Built-in features ### Configurations Create a `uno.config.js` or `uno.config.ts` configuration file the root-level of your project to customize UnoCSS. ```ts [uno.config.ts] import { defineConfig } from 'unocss' export default defineConfig({ cli: { entry: {}, // CliEntryItem | CliEntryItem[] }, // ... }) interface CliEntryItem { /** * Glob patterns to match files */ patterns: string[] /** * The output filename for the generated UnoCSS file */ outFile: string } ``` For a list of options, head over to the [UnoCSS configurations](/config/) docs. ## Options | Options | | | -------------------------- | --------------------------------------------------------------------------------------------------------- | | `-v, --version` | Display the current version of UnoCSS | | `-c, --config-file ` | Config file | | `-o, --out-file ` | The output filename for the generated UnoCSS file. Defaults to `uno.css` in the current working directory | | `--stdout` | Write the generated UnoCSS file to STDOUT. Will cause the `--watch` and `--out-file` being ignored | | `-w, --watch` | Indicates if the files found by the glob pattern should be watched | | `--preflights` | Enable preflight styles | | `--write-transformed` | Update source files with transformed utilities | | `-m, --minify` | Minify generated CSS | | `-h, --help` | Display available CLI options | --- # UnoCSS Documentation # Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/integrations/eslint.md # Path: docs/integrations/eslint.md --- title: UnoCSS ESLint Config description: ESLint config for UnoCSS (@unocss/eslint-config). --- # ESLint Config ESLint config for UnoCSS: `@unocss/eslint-config`. ## Installation ::: code-group ```bash [pnpm] pnpm add -D @unocss/eslint-config ``` ```bash [yarn] yarn add -D @unocss/eslint-config ``` ```bash [npm] npm install -D @unocss/eslint-config ``` ```bash [bun] bun add -D @unocss/eslint-config ``` ::: In [Flat Config Style](https://eslint.org/docs/latest/use/configure/configuration-files-new): ```js [eslint.config.js] import unocss from '@unocss/eslint-config/flat' export default [ unocss, // other configs ] ``` In legacy `.eslintrc` style: ```json [.eslintrc] { "extends": [ "@unocss" ] } ``` ## Rules - `@unocss/order` - Enforce a specific order for class selectors. - `@unocss/order-attributify` - Enforce a specific order for attributify selectors. - `@unocss/blocklist` - Disallow specific class selectors [Optional]. - `@unocss/enforce-class-compile` - Enforce class compile [Optional]. ### Rule options #### `@unocss/order` - `unoFunctions` (string[]) - mark function calls of matched names to enforce this rule. These are plain names, not patterns, case insensitive. Default: `['clsx', 'classnames']`. - `unoVariables` (string[]) - mark variable declarations of matched names to enforce this rule. These are regex patterns with flags `i`. Default: `['^cls', 'classNames?$']`. for example will match variable names `clsButton` and `buttonClassNames`. ### Optional rules These rules are not enabled by default. To enable it, add the following to your `.eslintrc`: ```json [.eslintrc] { "extends": [ "@unocss" ], "rules": { "@unocss/": "warn", // or "error", "@unocss/": ["warn" /* or "error" */, { /* options */ }] } } ``` #### `@unocss/blocklist` Throw warning or error when using utilities listed in `blocklist` get matched. You can customize messages for blocked rules to make them more informative and context-specific by using the `message` property of the meta object: ```ts [unocss.config.ts] export default defineConfig({ blocklist: [ ['bg-red-500', { message: 'Use bg-red-600 instead' }], [/-auto$/, { message: s => `Use ${s.replace(/-auto$/, '-a')} instead` }], // -> "my-auto" is in blocklist: Use "my-a" instead ], }) ``` #### `@unocss/enforce-class-compile` :wrench: _This rule is designed to work in combination with [compile class transformer](https://unocss.dev/transformers/compile-class)._ Throw warning or error when class attribute or directive doesn't start with `:uno:`. :wrench: automatically adds prefix `:uno:` to all class attributes and directives. Options: - `prefix` (string) - can be used in combination with [custom prefix](https://github.com/unocss/unocss/blob/main/packages-presets/transformer-compile-class/src/index.ts#L34). Default: `:uno:` - `enableFix` (boolean) - can be used for gradual migration when `false`. Default: `true` **Note**: currently only Vue supported. _Contribute a PR_ if you want this in JSX. If you're looking for this in Svelte, you might be looking for [`svelte-scoped`](https://unocss.dev/integrations/svelte-scoped) mode. ## Prior Arts Thanks to [eslint-plugin-unocss](https://github.com/devunt/eslint-plugin-unocss) by [@devunt](https://github.com/devunt). --- # UnoCSS Documentation # Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/integrations/index.md # Path: docs/integrations/index.md # Integrations ### Frameworks / Tools UnoCSS comes with integrations for various frameworks / tools: ### Examples Source code for all the examples can be found in the [/examples](https://github.com/unocss/unocss/tree/main/examples) directory. --- # UnoCSS Documentation # Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/integrations/jetbrains.md # Path: docs/integrations/jetbrains.md --- title: Community JetBrains Plugin for UnoCSS --- # JetBrains IDEs Plugin A community [plugin](https://github.com/re-ovo/unocss-intellij) that provides support for UnoCSS in JetBrains IDEs. :::info Note: This is a **community-maintained plugin, not reviewed or maintained by the UnoCSS team**. Please do your own research before using. If you have any issues with this plugin, please report it to [re-ovo/unocss-intellij](https://github.com/re-ovo/unocss-intellij). ::: ## Installation [JetBrains Marketplace](https://plugins.jetbrains.com/plugin/22204-unocss) ## Features - Auto-completion for UnoCSS classes - Hover documentation for UnoCSS classes - Code folding - Color/Icon preview ## Bug Reports / Feature Requests Report it at [Issue Tracker](https://github.com/re-ovo/unocss-intellij/issues) --- # UnoCSS Documentation # Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/integrations/lsp.md # Path: docs/integrations/lsp.md --- title: UnoCSS Language Server --- # LSP Support for UnoCSS UnoCSS Language Server provides IDE-like support for UnoCSS in any editor that supports LSP (Neovim, VS Code, Emacs, etc). :::info Note: This is a **community-maintained language server, not officially maintained by the UnoCSS team**. Use at your own discretion. Report issues at [xna00/unocss-language-server](https://github.com/xna00/unocss-language-server). ::: ## Installation ```bash npm install -g unocss-language-server ``` ## Features - Auto-completion for UnoCSS utilities - Hover documentation with CSS previews ## Usage Start the language server with: ```bash unocss-language-server --stdio ``` Configure your editor’s LSP client to connect to it. ## Bug Reports / Feature Requests Report it at [Issue Tracker](https://github.com/xna00/unocss-language-server/issues) --- # UnoCSS Documentation # Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/integrations/next.md # Path: docs/integrations/next.md --- title: Next.js description: Getting started with UnoCSS and Next.js. --- # Next.js Getting Started with UnoCSS and Next.js. Check the [example](https://github.com/unocss/unocss/tree/main/examples/next). ## Setup ### Installation ::: code-group ```bash [pnpm] pnpm add -D unocss @unocss/postcss @unocss/reset ``` ```bash [yarn] yarn add -D unocss @unocss/postcss @unocss/reset ``` ```bash [npm] npm install -D unocss @unocss/postcss @unocss/reset ``` ```bash [bun] bun add -D unocss @unocss/postcss @unocss/reset ``` ::: ### Configuration Create `uno.config.ts` or `uno.config.js` at the root of your project. ::: code-group ```ts [uno.config.ts] import { defineConfig, presetAttributify, presetIcons, presetWebFonts, presetWind3 } from 'unocss' export default defineConfig({ presets: [ presetWind3(), // ... ], }) ``` ```js [uno.config.js] import { defineConfig, presetAttributify, presetIcons, presetWebFonts, presetWind3 } from 'unocss' export default defineConfig({ presets: [ presetWind3(), // ... ], }) ``` ::: Create `postcss.config.mjs` at the root of your project. ```js [postcss.config.mjs] export default { plugins: { '@unocss/postcss': { content: ['./app/**/*.{html,js,ts,jsx,tsx}'], }, }, } ``` ### Import stylesheets Add `@unocss all;` in `globals.css`. ```css [globals.css] @unocss all; /* ... */ ``` Then import `@unocss/reset/tailwind.css` in your layout file. ::: code-group ```tsx [layout.tsx] import type { Metadata } from 'next' import { Geist, Geist_Mono } from 'next/font/google' import '@unocss/reset/tailwind.css' import './globals.css' const geistSans = Geist({ variable: '--font-geist-sans', subsets: ['latin'], }) const geistMono = Geist_Mono({ variable: '--font-geist-mono', subsets: ['latin'], }) export const metadata: Metadata = { title: 'Create Next App', description: 'Generated by create next app', } export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode }>) { return ( {children} ) } ``` ```js [layout.js] import { Geist, Geist_Mono } from 'next/font/google' import '@unocss/reset/tailwind.css' import './globals.css' const geistSans = Geist({ variable: '--font-geist-sans', subsets: ['latin'], }) const geistMono = Geist_Mono({ variable: '--font-geist-mono', subsets: ['latin'], }) export const metadata = { title: 'Create Next App', description: 'Generated by create next app', } export default function RootLayout({ children }) { return ( {children} ) } ``` ::: ## Usage Style your components with unocss! ::: code-group ```tsx [page.tsx] export default function Home() { return (
Nextjs
) } ``` ```js [page.js] export default function Home() { return (
Nextjs
) } ``` ::: ## License - MIT License © 2021-PRESENT [Anthony Fu](https://github.com/antfu) --- # UnoCSS Documentation # Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/integrations/nuxt.md # Path: docs/integrations/nuxt.md --- title: UnoCSS Nuxt Module description: Nuxt module for UnoCSS. --- # Nuxt Module The Nuxt module for UnoCSS. ## Installation ::: code-group ```bash [pnpm] pnpm add -D unocss @unocss/nuxt ``` ```bash [yarn] yarn add -D unocss @unocss/nuxt ``` ```bash [npm] npm install -D unocss @unocss/nuxt ``` ```bash [bun] bun add -D unocss @unocss/nuxt ``` ::: Add `@unocss/nuxt` to your Nuxt config file: ```ts [nuxt.config.ts] export default defineNuxtConfig({ modules: [ '@unocss/nuxt', ], }) ``` Create a `uno.config.ts` file: ```ts [uno.config.ts] import { defineConfig } from 'unocss' export default defineConfig({ // ...UnoCSS options }) ``` The `uno.css` entry will be automatically injected by the module. ## Support status | | Nuxt 2 | Nuxt Bridge | Nuxt 3 | | ------------- | :----- | :---------- | :----- | | Webpack Dev | ✅ | ✅ | 🚧 | | Webpack Build | ✅ | ✅ | ✅ | | Vite Dev | - | ✅ | ✅ | | Vite Build | - | ✅ | ✅ | ## Configuration We recommend to use the dedicated `uno.config.ts` file for configuration. See [Config File](/guide/config-file) for more details. You can enable the `nuxtLayers` option, so Nuxt will automatically merge `uno.config` files from each Nuxt layer: ```ts [nuxt.config.ts] export default defineNuxtConfig({ // ... unocss: { nuxtLayers: true, }, }) ``` then you can reexport the generated config in the root config file: ```ts [uno.config.ts] import config from './.nuxt/uno.config.mjs' export default config ``` or modify/extend it: ```ts import { mergeConfigs } from '@unocss/core' import config from './.nuxt/uno.config.mjs' export default mergeConfigs([config, { // your overrides }]) ``` ## License - MIT License © 2021-PRESENT [Anthony Fu](https://github.com/antfu) --- # UnoCSS Documentation # Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/integrations/postcss.md # Path: docs/integrations/postcss.md --- title: UnoCSS PostCSS Plugin outline: deep --- # PostCSS Plugin PostCSS plugin for UnoCSS. Supports `@apply`, `@screen` and `theme()` directives. [Source Code](https://github.com/unocss/unocss/tree/main/packages-integrations/postcss) ::: warning This package is in an experimental state right now. It doesn't follow semver, and may introduce breaking changes in patch versions. ::: ## Install ::: code-group ```bash [pnpm] pnpm add -D unocss @unocss/postcss ``` ```bash [yarn] yarn add -D unocss @unocss/postcss ``` ```bash [npm] npm install -D unocss @unocss/postcss ``` ```bash [bun] bun add -D unocss @unocss/postcss ``` ::: ```ts [postcss.config.mjs] import UnoCSS from '@unocss/postcss' export default { plugins: [ UnoCSS(), ], } ``` ```ts [uno.config.ts] import { defineConfig, presetWind3 } from 'unocss' export default defineConfig({ content: { filesystem: [ '**/*.{html,js,ts,jsx,tsx,vue,svelte,astro,marko}', ], }, presets: [ presetWind3(), ], }) ``` ```css [style.css] @unocss; ``` ## Usage ### `@unocss` `@unocss` at-rule is a placeholder. It will be replaced by the generated CSS. You can also inject each layer individually: ```css [style.css] @unocss preflights; @unocss default; /* Fallback layer. It's always recommended to include. Only unused layers will be injected here. */ @unocss; ``` If you want to include all layers no matter whether they are previously included or not, you can use `@unocss all`. This is useful if you want to include generated CSS in multiple files. ```css @unocss all; ``` Or if you want to exclude a specific layer, you can use the `@unocss !` directive: ```css @unocss !preflights, !; ``` ### `@apply` ```css .custom-div { @apply text-center my-0 font-medium; } ``` Will be transformed to: ```css .custom-div { margin-top: 0rem; margin-bottom: 0rem; text-align: center; font-weight: 500; } ``` ### `@screen` The `@screen` directive allows you to create media queries that reference your breakpoints by name comes from [`theme.breakpoints`](https://github.com/unocss/unocss/blob/main/README.md#extend-theme). ```css .grid { @apply grid grid-cols-2; } @screen xs { .grid { @apply grid-cols-1; } } @screen sm { .grid { @apply grid-cols-3; } } /* ... */ ``` Will be transformed to: ```css .grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); } @media (min-width: 320px) { .grid { grid-template-columns: repeat(1, minmax(0, 1fr)); } } @media (min-width: 640px) { .grid { grid-template-columns: repeat(3, minmax(0, 1fr)); } } /* ... */ ``` #### Breakpoint Variant Support `@screen` also supports `lt`、`at` variants ##### `@screen lt` ```css .grid { @apply grid grid-cols-2; } @screen lt-xs { .grid { @apply grid-cols-1; } } @screen lt-sm { .grid { @apply grid-cols-3; } } /* ... */ ``` Will be transformed to: ```css .grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); } @media (max-width: 319.9px) { .grid { grid-template-columns: repeat(1, minmax(0, 1fr)); } } @media (max-width: 639.9px) { .grid { grid-template-columns: repeat(3, minmax(0, 1fr)); } } /* ... */ ``` ##### `@screen at` ```css .grid { @apply grid grid-cols-2; } @screen at-xs { .grid { @apply grid-cols-1; } } @screen at-xl { .grid { @apply grid-cols-3; } } @screen at-xxl { .grid { @apply grid-cols-4; } } /* ... */ ``` Will be transformed to: ```css .grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); } @media (min-width: 320px) and (max-width: 639.9px) { .grid { grid-template-columns: repeat(1, minmax(0, 1fr)); } } @media (min-width: 1280px) and (max-width: 1535.9px) { .grid { grid-template-columns: repeat(3, minmax(0, 1fr)); } } @media (min-width: 1536px) { .grid { grid-template-columns: repeat(4, minmax(0, 1fr)); } } /* ... */ ``` ### `theme()` Use the `theme()` function to access your theme config values using dot notation. ```css .btn-blue { background-color: theme('colors.blue.500'); } ``` Will be compiled to: ```css .btn-blue { background-color: #3b82f6; } ``` --- # UnoCSS Documentation # Source: https://raw.githubusercontent.com/unocss/unocss/main/docs/integrations/runtime.md # Path: docs/integrations/runtime.md --- title: UnoCSS CDN Runtime description: CSS-in-JS runtime of UnoCSS (@unocss/runtime). outline: deep --- # Runtime UnoCSS runtime provide a CDN build that runs the UnoCSS right in the browser. It will detect the DOM changes and generate the styles on the fly. ## Usage Add the following line to your `index.html`: ```html [index.html] ``` The runtime may be configured by defining the configuration before loading the runtime: ```html ``` By default, the [Wind3 preset](/presets/wind3) is be applied. The runtime does not come with preflights, if you want to have style resets, you can either add your own, or use one from [Reset package](/guide/style-reset). ```html ``` ## Builds Several builds are available for different use cases. ### Uno (default) With `@unocss/preset-wind3` preset: ```html ``` ### Attributify With `@unocss/preset-wind3` and `@unocss/preset-attributify` presets: ```html ``` ### Mini With `@unocss/preset-mini` and `@unocss/preset-attributify` preset: ```html ``` ### Core If you need to mix and match presets, you can load only the core runtime and assign the presets manually. All the [official presets](/presets/#presets) from UnoCSS are available. Load the one you need before initializing the core runtime. ```html ``` ## Bundler Usage ```bash npm i @unocss/runtime ``` ```ts import initUnocssRuntime from '@unocss/runtime' initUnocssRuntime({ /* options */ }) ``` A UnoCSS config can be provided using the `defaults` property: ```ts import initUnocssRuntime from '@unocss/runtime' import config from './uno.config' initUnocssRuntime({ defaults: config }) ``` Presets can be imported from `esm.sh`: ```ts import { defineConfig } from '@unocss/runtime' import presetIcons from 'https://esm.sh/@unocss/preset-icons/browser' import presetWind3 from 'https://esm.sh/@unocss/preset-wind3' export default defineConfig({ presets: [presetWind3(), presetIcons({ cdn: 'https://esm.sh/' })], }) ``` ## Preventing FOUC Since UnoCSS runs after the DOM is ready, there can be a "flash of unstyled content" (FOUC) which may leads the user to see the page as unstyled. Use `un-cloak` attribute with CSS rules such as `[un-cloak] { display: none }` to hide the unstyled element until UnoCSS applies the styles for it. ::: code-group ```css [un-cloak] { display: none; } ``` ```html
This text will only be visible in blue color.
``` ::: --- # 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 | ` ``` With attributify mode, you can separate utilities into attributes: ```html ``` For example, `text-sm text-white` could be grouped into `text="sm white"` without duplicating the same prefix. ## Prefix self-referencing For utilities like `flex`, `grid`, `border`, that have the utilities same as the prefix, a special `~` value is provided. For example: ```html ``` Can be written as: ```html ``` ## Valueless attributify In addition to Windi CSS's attributify mode, this preset also supports valueless attributes. For example, ```html
``` now can be ```html
``` ::: info Note: If you are using JSX, `
` might be transformed to `
` 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` prop Text 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