Skip to content

图标预设

¥Icons preset

对 UnoCSS 使用纯 CSS 的任何图标。

¥Use any icon with Pure CSS for UnoCSS.

源代码

¥Source Code

提示

推荐阅读:纯 CSS 中的图标

¥Recommended reading: Icons in Pure CSS

请遵循以下约定使用图标

¥Follow the following conventions to use the icons

  • <prefix><collection>-<icon>

  • <prefix><collection>:<icon>

例如:

¥For example:

html
<!-- A basic anchor icon from Phosphor icons -->
<div class="i-ph-anchor-simple-thin" />
<!-- An orange alarm from Material Design Icons -->
<div class="i-mdi-alarm text-orange-400" />
<!-- A large Vue logo -->
<div class="i-logos-vue text-3xl" />
<!-- Sun in light mode, Moon in dark mode, from Carbon -->
<button class="i-carbon-sun dark:i-carbon-moon" />
<!-- Twemoji of laugh, turns to tear on hovering -->
<div class="i-twemoji-grinning-face-with-smiling-eyes hover:i-twemoji-face-with-tears-of-joy" />
Hover it

检查 所有可用的图标

¥Check all available icons.

安装

¥Install

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

我们使用 Iconify 作为图标的数据源。你需要按照 @iconify-json/* 模式在 devDependencies 中安装相应的图标集。例如,@iconify-json/mdi 对应 Material 设计图标@iconify-json/tabler 对应 Tabler。你可以参考 IcônesIconify 了解所有可用的集合。

¥We use Iconify 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, @iconify-json/tabler for Tabler. You can refer to Icônes or Iconify for all the collections available.

uno.config.ts
ts
import presetIcons from '@unocss/preset-icons'
import { defineConfig } from 'unocss'

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

提示

该预设包含在 unocss 包中,你也可以从那里导入它:

¥This preset is included in the unocss package, you can also import it from there:

ts
import { presetIcons } from 'unocss'

信息

你还可以单独使用此预设作为现有 UI 框架的补充,以获得纯 CSS 图标!

¥You can also use this preset alone as a complement to your existing UI frameworks to have pure CSS icons!

如果你希望一次安装 Iconify 上可用的所有图标集 (~130MB):

¥If you prefer to install all the icon sets available on Iconify at once (~130MB):

bash
pnpm add -D @iconify/json
bash
yarn add -D @iconify/json
bash
npm install -D @iconify/json

额外属性

¥Extra Properties

你可以提供额外的 CSS 属性来控制图标的默认行为。以下是默认内嵌图标的示例:

¥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. In some cases, you may want to explicitly set the rendering modes for each icon.

  • ?bgbackground-img - 将图标渲染为背景图片

    ¥?bg for background-img - renders the icon as a background image

  • ?maskmask - 将图标渲染为遮罩图片

    ¥?mask for mask - renders the icon as a mask image

例如,vscode-icons:file-type-light-pnpm,一个带有颜色的图标(svg 不包含 currentColor),将渲染为背景图片。使用 vscode-icons:file-type-light-pnpm?mask 将其渲染为遮罩图片并绕过其颜色。

¥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


<div class="w-full flex items-center justify-center gap-x-4 text-4xl p-2 mt-4">
  <div class="i-vscode-icons:file-type-light-pnpm" />
  <div class="i-vscode-icons:file-type-light-pnpm?mask text-red-300" />
</div>

配置集合和图标解析器

¥Configuring collections and icons resolvers

你可以通过 @iconify-json/[the-collection-you-want]@iconify/json 提供集合,或者使用 UnoCSS 配置上的 collections 选项使用自定义集合。

¥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

要加载 iconify 集合,你应该使用 @iconify-json/[the-collection-you-want] 而不是 @iconify/json,因为 json 文件很大。

¥To load iconify collections you should use @iconify-json/[the-collection-you-want] and not @iconify/json since the json file is huge.

打包器

¥Bundler

使用打包器时,你可以使用 dynamic imports 提供集合,以便它们将作为异步块打包器并按需加载。

¥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

或者,如果你更喜欢从 CDN 获取它们,则可以从 v0.32.10 开始指定 cdn 选项。我们推荐 esm.sh 作为 CDN 提供商。

¥Or if you prefer to fetch them from CDN, you can specify the cdn option since v0.32.10. We recommend esm.sh as the CDN provider.

ts
presetIcons({
  cdn: 'https://esm.sh/'
})

定制化

¥Customization

你还可以使用 CustomIconLoaderInlineCollection 提供你自己的自定义集合,例如使用 InlineCollection

¥You can also provide your own custom collections using CustomIconLoader or InlineCollection, for example using InlineCollection:

ts
presetIcons({
  collections: {
    custom: {
      circle: '<svg viewBox="0 0 120 120"><circle cx="60" cy="60" r="50"></circle></svg>',
      /* ... */
    },
    carbon: () => import('@iconify-json/carbon/icons.json').then(i => i.default as any),
    /* ... */
  }
})

然后,你可以在你的 html 上使用它:<span class="i-custom:circle"></span>

¥And then, you can use it on your html: <span class="i-custom:circle"></span>

Node.js

Node.js 中,预设会自动搜索已安装的 iconify 数据集,因此你无需注册 iconify 集合。

¥In Node.js the preset will search for the installed iconify dataset automatically, so you don't need to register the iconify collections.

你还可以使用 CustomIconLoaderInlineCollection 提供你自己的自定义集合。

¥You can also provide your own custom collections using also CustomIconLoader or InlineCollection.

FileSystemIconLoader

此外,你还可以使用 FileSystemIconLoader 从文件系统加载自定义图标。你需要将 @iconify/utils 软件包安装为 dev dependency

¥Additionally, you can also use FileSystemIconLoader to load your custom icons from your file system. You will need to install @iconify/utils package as dev dependency.

unocss.config.ts
ts
import fs from 'node:fs/promises'
import { defineConfig, presetIcons } from 'unocss'

// loader helpers
import { FileSystemIconLoader } from '@iconify/utils/lib/loader/node-loaders'

export default defineConfig({
  presets: [
    presetIcons({
      collections: {
        // key as the collection name
        'my-icons': {
          account: '<svg><!-- ... --></svg>',
          // 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

@iconify/utils v2.1.20 开始,你可以使用其他包通过新的 createExternalPackageIconLoader 辅助程序加载其他作者的图标。

¥From @iconify/utils v2.1.20 you can use other packages to load icons from others authors using the new createExternalPackageIconLoader helper.

WARNING

外部包必须包含 icons.json 文件以及 IconifyJSON 格式的 icons 数据,该文件可以使用 Iconify Tools 导出。检查 将图标集导出为 JSON 包 了解更多详细信息。

¥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 for more details.

例如,你可以使用 an-awesome-collection@my-awesome-collections/some-collection 加载自定义或第三方图标:

¥For example, you can use an-awesome-collection or @my-awesome-collections/some-collection to load your custom or third party icons:

unocss.config.ts
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:

unocss.config.ts
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(/^<svg /, '<svg fill="currentColor" ')
        )
      }
    })
  ]
})

图标定制

¥Icon Customizations

你可以使用 customizations 配置选项自定义所有图标。

¥You can customize all icons using customizations configuration option.

可用的自定义功能:

¥Available customizations functions:

  • transform:转换原始 svg,仅在使用 custom 图标集合(iconify 集合除外)时应用。

    ¥transform: transform raw svg, will be only applied when using custom icon collection (iconify collections excluded).

  • customize:更改默认图标自定义值。

    ¥customize: change default icon customizations values.

  • iconCustomizer:更改默认图标自定义值。

    ¥iconCustomizer: change default icon customizations values.

对于每个加载的图标,自定义将按以下顺序应用:

¥For each loaded icon, the customizations will be applied in this order:

  • transform 应用到原始 svg(如果提供)并使用自定义图标集合

    ¥apply transform to raw svg, if provided and using custom icon collection

  • 应用带有默认自定义的 customize(如果提供)

    ¥apply customize with default customizations, if provided

  • 应用 iconCustomizercustomize 自定义(如果提供)

    ¥apply iconCustomizer with customize customizations, if provided

全局自定义图标转换

¥Global Custom Icon Transformation

加载自定义图标时,你可以对其进行转换,例如添加 fill 属性和 currentColor

¥When loading your custom icons, you can transform them, for example adding fill attribute with currentColor:

ts
presetIcons({
  customizations: {
    transform(svg) {
      return svg.replace(/#fff/, 'currentColor')
    }
  }
})

从版本 0.30.8 开始,transform 提供 collectionicon 名称:

¥From version 0.30.8 the transform provides the collection and icon names:

ts
presetIcons({
  customizations: {
    transform(svg, collection, icon) {
      // do not apply fill to this icons on this collection
      if (collection === 'custom' && icon === 'my-icon')
        return svg
      return svg.replace(/#fff/, 'currentColor')
    }
  }
})

全局图标定制

¥Global Icon Customization

加载任何图标时,你可以为所有图标自定义通用属性,例如配置相同的大小:

¥When loading any icon you can customize common properties to all of them, for example configuring the same size:

ts
presetIcons({
  customizations: {
    customize(props) {
      props.width = '2em'
      props.height = '2em'
      return props
    }
  }
})

图标/集合定制

¥Icon/Collection Customization

你可以使用 iconCustomizer 配置选项自定义每个图标。

¥You can customize each icon using iconCustomizer configuration option.

iconCustomizer 将优先于配置。

¥The iconCustomizer will take precedence over configuration.

iconCustomizer 将应用于任何集合,即 custom 加载器、custom collections 上的 inlined@iconify 中的每个图标。

¥The iconCustomizer will be applied to any collection, that is, for each icon from custom loader, inlined on custom collections or from @iconify.

例如,你可以配置 iconCustomizer 来更改集合的所有图标或集合上的单个图标:

¥For example, you can configure iconCustomizer to change all icons for a collection or individual icons on a collection:

ts
presetIcons({
  customizations: {
    iconCustomizer(collection, icon, props) {
      // customize all icons in this collection
      if (collection === 'my-other-icons') {
        props.width = '4em'
        props.height = '4em'
      }
      // customize this icon in this collection
      if (collection === 'my-icons' && icon === 'account') {
        props.width = '6em'
        props.height = '6em'
      }
      // customize this @iconify icon in this collection
      if (collection === 'mdi' && icon === 'account') {
        props.width = '2em'
        props.height = '2em'
      }
    }
  }
})

指令

¥Directives

你可以在 CSS 中使用 icon() 指令来获取图标的元数据。

¥You can use the icon() directive in your CSS to get the metadata of the icon.

css
.icon {
  background-image: icon('i-carbon-sun');
}

警告

icon() 依赖于 @unocss/preset-icons 并将使用配置,请确保你已添加此预设。

¥icon() depends on @unocss/preset-icons and will use the configuration, make sure you have added this preset.

有关 icon() 指令的更多信息,请查看 指令

¥More about icon() directive, check Directives.

选项

¥Options

scale

  • 类型:number

    ¥Type: number

  • 默认:1

    ¥Default: 1

与当前字体大小相关的比例 (1em)。

¥Scale related to the current font size (1em).

mode

生成 CSS 图标的模式。

¥Mode of generated CSS icons.

提示

  • mask - 对单色图标使用背景颜色和 mask 属性

    ¥mask - use background color and the mask property for monochrome icons

  • bg - 使用图标的背景图片,颜色是静态的

    ¥bg - use background image for the icons, colors are static

  • auto - 根据每个图标的样式智能地决定 maskbg 之间的模式

    ¥auto - smartly decide mode between mask and bg per icon based on its style

prefix

  • 类型:string | string[]

    ¥Type: string | string[]

  • 默认:'i-'

    ¥Default: 'i-'

用于匹配图标规则的类前缀。

¥Class prefix for matching icon rules.

extraProperties

  • 类型:Record<string, string>

    ¥Type: Record<string, string>

  • 默认:{}

    ¥Default: {}

应用于生成的 CSS 的额外 CSS 属性。

¥Extra CSS properties applied to the generated CSS.

warn

  • 类型:boolean

    ¥Type: boolean

  • 默认:false

    ¥Default: false

当缺少的图标匹配时触发警告。

¥Emit warning when missing icons are matched.

collections

  • 类型:Record<string, (() => Awaitable<IconifyJSON>) | undefined | CustomIconLoader | InlineCollection>

    ¥Type: Record<string, (() => Awaitable<IconifyJSON>) | undefined | CustomIconLoader | InlineCollection>

  • 默认:undefined

    ¥Default: undefined

在 Node.js 环境中,预设会自动搜索已安装的 iconify 数据集。在浏览器中使用时,提供此选项是为了向数据集提供自定义加载机制。

¥In Node.js environment, the preset will search for the installed iconify dataset automatically. When using in the browser, this options is provided to provide dataset with custom loading mechanism.

layer

  • 类型:string

    ¥Type: string

  • 默认:'icons'

    ¥Default: 'icons'

规则层。

¥Rule layer.

customizations

  • 类型:Omit<IconCustomizations, 'additionalProps' | 'trimCustomSvg'>

    ¥Type: Omit<IconCustomizations, 'additionalProps' | 'trimCustomSvg'>

  • 默认:undefined

    ¥Default: undefined

自定义图标定制。

¥Custom icon customizations.

autoInstall

  • 类型:boolean

    ¥Type: boolean

  • 默认:false

    ¥Default: false

检测到使用情况时自动安装图标源包。

¥Auto install icon sources package when the usages is detected.

警告

仅在 node 环境下,在 browser 上此选项将被忽略。

¥Only on node environment, on browser this option will be ignored.

unit

  • 类型:string

    ¥Type: string

  • 默认:'em'

    ¥Default: 'em'

自定义图标单元。

¥Custom icon unit.

cdn

  • 类型:string

    ¥Type: string

  • 默认:undefined

    ¥Default: undefined

从 CDN 加载图标。应以 https:// 开始并以 / 结束。

¥Load icons from CDN. Should starts with https:// and ends with /.

推荐:

¥Recommends:

  • https://esm.sh/

  • https://cdn.skypack.dev/

customFetch

  • 类型:(url: string) => Promise<any>

    ¥Type: (url: string) => Promise<any>

  • 默认:undefined

    ¥Default: undefined

Preset 使用 ofetch 作为默认的 fetcher,你也可以自定义 fetch 函数来提供图标数据。

¥Preset used ofetch as the default fetcher, you can also custom fetch function to provide the icon data.

processor

  • 类型:(cssObject: CSSObject, meta: Required<IconMeta>) => void

    ¥Type: (cssObject: CSSObject, meta: Required<IconMeta>) => void

  • 默认:undefined

    ¥Default: undefined

ts
interface IconMeta {
  collection: string
  icon: string
  svg: string
  mode?: IconsOptions['mode']
}

stringify 之前 CSS 对象的处理器。参见 example

¥Processor for the CSS object before stringify. See example.

高级自定义图标集清理

¥Advanced Custom Icon Set Cleanup

将此预设与自定义图标一起使用时,请考虑使用类似于 Iconify 对任何图标集执行的清理过程。你需要的所有工具都可以在 Iconify 工具 中找到。

¥When using this preset with your custom icons, consider using a cleanup process similar to that done by Iconify for any icons sets. All the tools you need are available in Iconify Tools.

你可以在 Vue 3 项目上使用此预设来检查此存储库:@iconify/tools/@iconify-demo/unocss

¥You can check this repo, using this preset on a Vue 3 project: @iconify/tools/@iconify-demo/unocss.

阅读 Iconify清理图标 文章了解更多详细信息。

¥Read Cleaning up icons article from Iconify for more details.

致谢

¥Credits