Icons with UnoCSS
If you are using UnoCSS, you can easily use over 200,000 open source icons and custom icons with minimal code.
Among other features, UnoCSS has @unocss/preset-icons package that dynamically generates icons. It uses icon data from Iconify.
Usage
To use icons with UnoCSS, add @unocss/preset-icons preset to config:
import presetIcons from '@unocss/preset-icons';
UnoCSS({
presets: [
presetIcons({
/* options */
}),
// ...other presets
],
});
In your code add element with the following class name: "i-" + icon set prefix + "-" + icon name.
Examples:
<span class="i-carbon-logo-github"></span>
<span class="i-mdi-light-home"></span>
It is that simple.
For more information, see README file in preset-icons package.
Icon size
Be aware that by default, UnoCSS scales icons to 1.2em.
You can change that by changing scale option.
If you want to change width and height separately or make icon square, you can use customize option. See below.
Custom icons
You can use UnoCSS with custom icons. During the build process, you can import, clean up and optimise icons using Iconify Tools.
See demo from Iconify Tools package. Configuration is in unocss.config.ts.
Functions used in that config file are documented in Iconify Tools section of this documentation.
Customise icons
You can customise icons using customize option.
Option customize is part of customizations option, it is a function has 3 parameters:
- customisations that can be used for flip or rotate icon.
- data, IconifyIcon with icon data.
- name, string with icon name in "prefix:name" format.
The first parameter is a legacy option, it is not really useful.
Icon data is a mutable object, you can change it to customise icon. You can change colors in icons that have hardcoded palette, opacity, timing for animations, add additional shapes and so on... You can also resize icon or add padding by messing with width, height, left and top properties.
See IconifyIcon type for icon data format.
Icon name lets you know which icon you are customizing.
Examples
Making all icons square:
presetIcons({
customizations: {
customize: (defaultCustomizations, data, name) => {
// Make icon square
const width = data.width ?? 16;
const height = data.height ?? 16;
if (height > width) {
// Set width to match height
data.width = height;
// Center icon horizontally by changing viewBox left position
data.left = (data.left ?? 0) - (height - width) / 2;
}
return defaultCustomizations
},
}
})
Changing color:
presetIcons({
customizations: {
customize: (defaultCustomizations, data, name) => {
if (name === 'twemoji:blue-square') {
// Turn blue square into red square
data.body = data.body.replaceAll('#55ACEE', '#e83933')
}
return defaultCustomizations
},
}
})
If something is not working, don't forget that you can always console.log(data) to see icon data.