主题
图标预设
🌐 Icons preset
对 UnoCSS 使用纯 CSS 的任何图标。
🌐 Use any icon with Pure CSS for UnoCSS.
TIP
推荐阅读:纯 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" /> 将鼠标悬停在上面
查看所有可用图标。
🌐 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]bash
bun add -D @unocss/preset-icons @iconify-json/[the-collection-you-want]我们使用 Iconify 作为我们的图标数据源。你需要按照 @iconify-json/* 的模式在 devDependencies 中安装相应的图标集。例如,@iconify-json/mdi 对应 Material Design Icons,@iconify-json/tabler 对应 Tabler。你可以参考 Icônes 或 Iconify 查看所有可用的图标集合。
🌐 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.
ts
import presetIcons from '@unocss/preset-icons'
import { defineConfig } from 'unocss'
export default defineConfig({
presets: [
presetIcons({ /* options */ }),
// ...other presets
],
})TIP
此预设包含在 unocss 包中,你也可以从那里导入它:
ts
import { presetIcons } from 'unocss'INFO
你还可以单独使用此预设作为现有 UI 框架的补充,以获得纯 CSS 图标!
如果你希望一次安装 Iconify 上可用的所有图标集 (~130MB):
🌐 If you prefer to install all the icon sets available on Iconify at once (~130MB):
bash
pnpm add -D @iconify/jsonbash
yarn add -D @iconify/jsonbash
npm install -D @iconify/jsonbash
bun add -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.
?bg用于background-img- 将图标作为背景图片显示?mask用于mask- 将图标渲染为蒙版图片
例如,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
你也可以使用 CustomIconLoader 或 InlineCollection 提供你自己的自定义集合,例如使用 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),
/* ... */
}
})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.
你也可以使用 CustomIconLoader 或 InlineCollection 提供你自己的自定义集合。
🌐 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.
ts
import fs from 'node:fs/promises'
// loader helpers
import { FileSystemIconLoader } from '@iconify/utils/lib/loader/node-loaders'
import { defineConfig, presetIcons } from 'unocss'
export default defineConfig({
presets: [
presetIcons({
collections: {
// key as the collection name
'my-icons': {
account: '<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.
警告
外部包必须包含带有 icons 数据的 icons.json 文件,格式为 IconifyJSON,可以使用 Iconify 工具导出。有关详细信息,请查看 将图标集导出为 JSON 包 。
例如,你可以使用 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:
ts
import { createExternalPackageIconLoader } from '@iconify/utils/lib/loader/external-pkg'
import { defineConfig, presetIcons } from 'unocss'
export default defineConfig({
presets: [
presetIcons({
collections: createExternalPackageIconLoader('an-awesome-collection')
})
]
})你还可以将其与其他自定义图标加载器结合使用,例如:
🌐 You can also combine it with other custom icon loaders, for example:
ts
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集合)。customize:更改默认图标自定义值。iconCustomizer:更改默认图标自定义值。
对于每个加载的图标,自定义将按以下顺序应用:
🌐 For each loaded icon, the customizations will be applied in this order:
- 将
transform应用于原始svg,如果提供并使用自定义图标集合 - 如果提供,则使用默认自定义应用
customize - 应用
iconCustomizer并使用提供的customize自定义设置
全局自定义图标转换
🌐 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 提供了 collection 和 icon 的名称:
🌐 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');
}WARNING
icon() 依赖于 @unocss/preset-icons 并将使用该配置,确保你已添加此预设。
关于 icon() 指令的更多信息,请查阅 指令。
🌐 More about icon() directive, check Directives.
选项
🌐 Options
scale
- 类型:
number - 默认:
1
与当前字体大小相关的比例 (1em)。
🌐 Scale related to the current font size (1em).
mode
- 类型:
'mask' | 'bg' | 'auto' - 默认:
'auto' - 请参见:https://antfu.me/posts/icons-in-pure-css
生成 CSS 图标的模式。
🌐 Mode of generated CSS icons.
TIP
mask- 为单色图标使用背景颜色和mask属性bg- 使用图标的背景图片,颜色是静态的auto- 根据图标的样式智能地在mask和bg模式之间选择
prefix
- 类型:
string | string[] - 默认:
'i-'
用于匹配图标规则的类前缀。
🌐 Class prefix for matching icon rules.
extraProperties
- 类型:
Record<string, string> - 默认:
{}
应用于生成的 CSS 的额外 CSS 属性。
🌐 Extra CSS properties applied to the generated CSS.
warn
- 类型:
boolean - 默认:
false
当缺少的图标匹配时触发警告。
🌐 Emit warning when missing icons are matched.
iconifyCollectionsNames
- 类型:
string[] - 默认:
undefined
可使用的其他 @iconify-json 收藏。 当存在默认图标预设集合名称中未列出的新 @iconify-json 收藏时,应使用此选项。
🌐 Additional @iconify-json collections to use. This option should be used when there are new @iconify-json collections not listed in the default icons preset collection names.
collections
- 类型:
Record<string, (() => Awaitable<IconifyJSON>) | undefined | CustomIconLoader | InlineCollection> - 默认:
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 - 默认:
'icons'
规则层。
🌐 Rule layer.
customizations
- 类型:
Omit<IconCustomizations, 'additionalProps' | 'trimCustomSvg'> - 默认:
undefined
自定义图标定制。
🌐 Custom icon customizations.
autoInstall
- 类型:
boolean - 默认:
false
检测到使用情况时自动安装图标源包。
🌐 Auto install icon sources package when the usages is detected.
WARNING
只有在 node 环境下,此选项才会生效,在 browser 环境中将被忽略。
unit
- 类型:
string - 默认:
'em'
自定义图标单元。
🌐 Custom icon unit.
cdn
- 类型:
string - 默认:
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> - 默认:
undefined
预设使用 ofetch 作为默认获取器,你也可以自定义获取函数来提供图标数据。
🌐 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 - 默认:
undefined
ts
interface IconMeta {
collection: string
icon: string
svg: string
mode?: IconsOptions['mode']
}在将 CSS 对象转为字符串之前处理它的处理器。参见 示例。
🌐 Processor for the CSS object before stringify. See example.
高级自定义图标集清理
🌐 Advanced Custom Icon Set Cleanup
在使用此预设搭配自定义图标时,建议对任何图标集使用类似 Iconify 所做的清理流程。你所需的所有工具都可以在 Iconify Tools 中找到。
🌐 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.
🌐 Read Cleaning up icons article from Iconify for more details.
可访问性问题
🌐 Accessibility Concerns
在使用图标时,考虑到所有潜在用户非常重要。其中一些用户可能正在使用屏幕阅读器,他们需要一个替代文本来理解图标的含义。你可以使用 aria-label 属性来提供图标的描述:
🌐 When using icons, it's important to take all your potential users into account. Some of them might be using screen readers, and they will need an alternative text to understand what an icon means. You can use the aria-label attribute to provide a description of the icon:
html
<a href="/profile" aria-label="Profile" class="i-ph:user-duotone"></a>如果图标只是装饰性的,并且不需要文本替代,可以使用 aria-hidden="true" 将其从屏幕阅读器中隐藏:
🌐 If the icon is purely decorative and doesn't need a text alternative, you can use aria-hidden="true" to hide it from screen readers:
html
<a href="/profile">
<span aria-hidden="true" class="i-ph:user-duotone"></span>
My Profile
</a>还有许多其他方法可以为屏幕阅读器提供提示文本,例如,Wind3 预设 包含 sr-only,可以在视觉上隐藏元素,但仍让屏幕阅读器可以访问。
🌐 There are many other techniques to provide hint text for screen-readers, for instance, Wind3 preset includes sr-only to hide elements visually but keep them accessible to screen readers.
你可以在网络上找到一些有关图标可访问性的好资源,CSS 图标的行为类似于图标字体,因此你可以使用与图标字体相同的技术。
🌐 You can find some good resources on the web about icons accessibility, and CSS icons behave like icon fonts, so you can use the same techniques as you would with icon fonts.
致谢
🌐 Credits