Iconify 文档

Iconify 图标框架的使用说明。

Api

Api

cdn

title: Building Custom Budget Content Delivery Network

Custom budget CDN

This tutorial is a part of Iconify API hosting instructions.

What is CDN? CDN is short for content delivery network. It is a set of servers spread out across the globe that deliver content to a visitor as fast as possible. AnyCast DNS connects visitors to the closest server.

This tutorial is intended to be used if you are setting up your custom Iconify API and want to take advantage of CDN.

Stateless CDN

This tutorial is intended for stateless CDN.

Stateless means every request does not depend on previous request, so if a visitor is connected to a different edge server than he visited before, it wouldn't make any difference.

Iconify API is stateless. It does not allow visitors to store anything, it does not track anything, it does not send any cookies. There is no central server, and each API server works separately from other servers.

Setting up edge servers

First, you need to create multiple origin servers in various parts of the world.

All servers need to be configured to serve exactly the same data for exactly the same host name. You need to configure multiple identical servers. There are plenty of tools that can automate this process; however, they are not part of this tutorial.

For tutorial on how to set up hosting for Iconify API, see hosting tutorial.

Route53

After setting up multiple servers, you want to direct users to the closest server.

Adding multiple [str]A records to your domain won't achieve that. You need AnyCast DNS.

AnyCast DNS is expensive. Very expensive. What if you don't have thousands of dollars to spend? Good news is there is one alternative solution: Amazon's Route53 latency routing.

Route53 latency routing works by redirecting the visitor to the closest Amazon datacenter.

What if you are not hosting your websites at Amazon datacenters? You can host at datacenters not far from Amazon (same country or state), which is more than good enough to redirect visitors to the closest of your servers.

Setting up Route53

Then you need to add records for each server you have in your CDN. Click [str]Create Record Set, enter subdomain name in [str]Name field, enter IP address in [str]Value field, in [str]Routing Policy field select [str]Latency. That last part is very important: that makes it possible to redirect visitors to the closest server based on latency. Select the region closest to your server's physical location, enter something in [str]Set ID field.

If you are running script on AWS service, instead of entering IP select click [str]Yes for [str]Alias option and select AWS instance.

Adding a new record to Route53

Click [str]Create button to add that record.

Create several more records for your other servers. For each record enter the same subdomain, but different IP and a different region.

By the time you are finished, it should look like this:

Route53 records

Notice there are 3 records for [str]icons.simplesvg.com pointing to different IP addresses with different region set up.

That's it. When visiting [url]icons.simplesvg.com, user will be redirected to one of 3 IPs: 1.2.3.4, 2.3.4.5, 3.4.5.6 depending on which AWS datacenter is the closest. It is precise enough to create a budget custom CDN.

Host name used in this example, [str]icons.simplesvg.com, is just an example. It was used at start of this project. It is deprecated and should not be used.

Iconify API

This method is used to host Iconify API, hosted at [url]api.iconify.design.

Api

collection

title: List of icons
types:
  IconifyJSON: '../types/iconify-json.md'
  IconifyInfo: '../types/iconify-info.md'

List of icons

You can get a list of icons in an icon set sets using [url]/collection API query.

Query

API query is [url]/collection.

Required parameter:

Optional parameters:

Response

Response is a complex object with the following required properties:

Then there are many optional properties.

Icons

Properties that are relevant for a list of icons:

To get a list of all icon names that should be shown, use the following logic:

To get all icon names, add to the result above:

Other properties

Other optional properties:

See [type]IconifyJSON type and metadata documentation.

Only icon sets that have info can be browsed. If you want to hide an icon set, do not set the info object when importing it.

Simple example

This is a basic icon set, without categories or any extra metadata:

hint: /collection?prefix=mdi-light&pretty=1
src: api/collection-mdi-light.json

Actual API response is a lot bigger. Example was reduced.

Categories example

Icon set in example below:

hint: /collection?prefix=line-md&pretty=1
src: api/collection-line-md.json

Actual API response is a lot bigger. Example was reduced.

Error response

If an icon set is not found or cannot be browsed, server returns [num]404 HTTP error.

If browsing icons is disabled, route is not handled, server returns [num]404 HTTP error.

Type

Type for API response:

import type { IconifyInfo, IconifyJSON } from '@iconify/types';

export interface APIv2CollectionResponse {
	// Icon set prefix
	prefix: string;

	// Number of icons (duplicate of info?.total)
	total: number;

	// Icon set title, if available (duplicate of info?.name)
	title?: string;

	// Icon set info
	info?: IconifyInfo;

	// List of icons without categories
	uncategorized?: string[];

	// List of icons, sorted by category
	categories?: Record<string, string[]>;

	// List of hidden icons
	hidden?: string[];

	// List of aliases, key = alias, value = parent icon
	aliases?: Record<string, string>;

	// Characters, key = character, value = icon name
	chars?: Record<string, string>;

	// Themes
	themes?: IconifyJSON['themes'];
	prefixes?: IconifyJSON['prefixes'];
	suffixes?: IconifyJSON['suffixes'];
}
Api

collections

title: List of icon sets
types:
  IconifyInfo: '../types/iconify-info.md'

List of icon sets

You can get list of available icon sets using [url]/collections API query.

Query

API query is [url]/collections.

Optional parameters:

Response is an object, where key is icon set prefix, value is [type]IconifyInfo object.

Only icon sets that have info will be returned. If you want to hide an icon set, do not set the info object when importing it.

hint: /collections?prefixes=fa,fa-,fa6-&pretty=1
src: api/collections.json

Error response

If browsing icons is disabled, route is not handled, server returns [num]404 HTTP error.

Type

import type { IconifyInfo } from '@iconify/types';

export type APIv2CollectionsList = Record<string, IconifyInfo>;
Api

config

title: Configuring custom Iconify API
replacements:
  - code: '/2/2.0.0/'
    value: '/${svg-framework.version.major}/${svg-framework.version.full}/'

Configuring custom Iconify API

This article explains who to configure Iconify icon components to use custom API server.

All Iconify icon components can connect to multiple Iconify API servers. It is done via API providers.

If you are hosting Iconify API server, there are 2 ways to use your icons:

As far as code is concerned, both choices are actually almost identical. The only difference is in first option provider id is empty string [str]"", so you are overwriting existing configuration instead of adding new one.

Your users can do whatever they want: overwrite default API provider or add new API provider. They can use whatever provider id they want for it, as long as they use the same provider id in icon names.

Example

For example, you have set up your Iconify API server at [url]https://iconify.myproject.tld.

One of icon sets you host has prefix [icon]material-icons and it has icon [icon]home.

How can your users configure it?

Overwriting default API

Users can overwrite the default API provider like this:

import { addAPIProvider } from '@iconify/react';

addAPIProvider('', {
	resources: ['https://iconify.myproject.tld'],
});

then in components use your icon like this:

import React from 'react';
import { Icon } from '@iconify/react';

function renderHomeIcon() {
	return <Icon icon="material-icons:home" />;
}

Using custom ID

Users can also set any id for your API:

import { addAPIProvider } from '@iconify/react';

addAPIProvider('awesome-icons', {
	resources: ['https://iconify.myproject.tld'],
});

then in components use your icon like this:

import React from 'react';
import { Icon } from '@iconify/react';

function renderHomeIcon() {
	return <Icon icon="@awesome-icons:material-icons:home" />;
}

Whatever your users choose, it is up to them. API server does not know what ID users use in icon names and cannot change it.

So one user can overwrite public Iconify API configuration, another user can set ID to [icon]awesome-icons, another user can set ID to [icon]more-icons and so on.

Using IconifyProviders

Instead of using [func]addAPIProvider(), users can use global variable [var]IconifyProviders to set configuration.

<script>
	// Define global variable
	IconifyProviders = {
		// For overwriting public API
		'': {
			resources: ['https://iconify.myproject.tld'],
		},

		// For creating alternative API provider
		// 'awesome-icons': {
		// 	resources: ['https://iconify.myproject.tld'],
		// },
	};
</script>
<script src="/assets/bundle.min.js"></script>

This example assumes that [url]/assets/bundle.min.js is a bundle that contains all components that use icons and Iconify component.

Similar example for the SVG framework:

<head>
	<script>
		// Define global variable
		IconifyProviders = {
			// For overwriting public API
			// '': {
			// 	resources: ['https://iconify.myproject.tld'],
			// },

			// For creating alternative API provider
			'awesome-icons': {
				resources: ['https://iconify.myproject.tld'],
			},
		};
	</script>
	<script src="https://code.iconify.design/2/2.0.0/iconify.min.js"></script>
</head>
<body>
	<span class="iconify" data-icon="@awesome-icons:material-icons:home"></span>
</body>

For more information about API providers, see API providers documentation.

Api

css

title: Generating CSS for icons
functions:
  getIconsCSS: '/docs/libraries/utils/get-icons-css.md'

CSS for icons

Iconify API can dynamically generate CSS for icons, where icons are used as background or mask image.

This allows rendering icons with a simple [tag]span tag without any components.

Query

API URI that generates CSS is [url]/{prefix}.css?icons={icons}, where:

Examples:

hint: /openmoji.css?icons=axe,balance-scale
src: api/openmoji.css
hint: /mdi.css?icons=account-box,account-cash,account,home
src: api/mdi.css

Using icons in HTML is easy: use a placeholder element with 2 class names: class name for an icon set and class name for icon:

<span class="icon--openmoji icon--openmoji--axe"></span>
<span class="icon--mdi icon--mdi--account"></span>

Why 2 classes? This allows splitting common style in separate rule, reducing duplication and making it easier to target all icons from an icon set.

If you want to reference icons with 1 simple class, you can use [prop]selector and [prop]common options. See examples below.

Options

Optional parameters:

Other optional parameters are the same as in [func]getIconsCSS() function of Iconify Utils.

Color and mode

There are two types of icons:

You can use both types in CSS.

Icons with hardcoded palette are rendered as background images:

include common/icon-types-palette

Monotone icons are rendered as mask images with background color set to [prop]currentColor:

include common/icon-types-monotone

Using [prop]currentColor as background color makes it easy to change icon color by changing text color:

<span class="icon--bi icon--bi--bell-fill" style="color: green"></span>

You can force background or mask mode by adding [prop]mode parameter: [url]&mode=background or [url]&mode=mask

You can also use [prop]color parameter to convert monotone icons to icons with palette: [url]&color=green.

CSS variables

include: libraries/utils/css-color
<span class="icon--mdi icon--mdi--home" style="color: var(--icon-color)"></span>

More examples

You can customise generated stylesheet using various optional parameters.

Getting CSS for one icon with custom selector by adding [prop]selector parameter:

hint: /openmoji.css?icons=axe&selector=.axe-icon
src: api/openmoji-axe.css

CSS for one icon with a pseudo selector, using [prop]selector and [prop]selector parameters:

hint: /material-symbols.css?icons=check-box-outline-rounded&selector=.checkbox-checked::after&pseudo=1
src: api/checkbox.css

Same as above, but sets icon color to green:

hint: /material-symbols.css?icons=check-box-outline-rounded&selector=.checkbox-checked::after&pseudo=1&color=green
src: api/checkbox-color.css

CSS for multiple icons with pseudo selectors requires multiple parameters. It requires using at least [prop]icon and [prop]pseudo parameters, optionally with [prop]common and [prop]override parameters:

hint: /line-md.css?icons=account-add,account-delete&selector=.icon--{prefix}--{name}::after&pseudo=1
src: api/line-md.css
hint: /line-md.css?icons=account-add,account-delete&selector=.icon--{prefix}--{name}::after&common=.icon--{prefix}::after&override=.icon--{prefix}.icon--{prefix}--{name}::after&pseudo=1
src: api/line-md2.css

Want to support old browsers? Add [url]&var=null:

hint: /openmoji.css?icons=axe,balance-scale&var=null
src: api/openmoji-novar.css

... which might result in duplicate content for monotone icons:

hint: /line-md.css?icons=account-add,account-delete&var=null
src: api/line-md-novar.css

See [func]getIconsCSS() function of Iconify Utils for more examples.

Api

Hosting Iconify API

This article explains how to host Iconify on your server, so your website does not rely on Iconify public API servers.

Iconify API software is available as Node.js script.

Django Iconify

In addition to Iconify API mentioned above, there is a community created alternative for Django users: django-iconify.

See django-iconify project page for configuration options and usage.

Source code

Everything you need is available at Iconify GitHub repositories:

Node.js API {#node}

See Iconify API: Node.js for installation and configuration instructions.

API network

Iconify public API is hosted on multiple servers that form custom CDN. They are located in different parts of the world, and visitors are always redirected to the closest server.

How does CDN help? By connecting visitors to the closest server, latency is greatly reduced:

Additional servers may be added in other regions when needed.

How else does it help? Redundancy. Downtime happens. If one server has issues, you can quickly disable it and visitors will be routed to a different server. There are tools to automate it, such as Route 53 health checks.

Would you like to set up your own CDN for Iconify API? See setting up custom CDN tutorial.

For added security, Iconify public API also CloudFlare service. However, that does not change anything. Instead of connecting visitor to the closest server, CDN is used to connect CloudFlare edge server to the closest API. Iconify API still greatly benefits from latency reduction offered by a custom CDN.

Api

icon-data

title: Icon data on demand
types:
  IconifyJSON: '../types/iconify-json.md'

Icon data on demand

Main feature of Iconify icon components is ability to load icon data on demand.

Instead of bundling icons, developer passes icon name to icon component, data for used icons is loaded from Iconify API. This approach has the following advantages:

Process

How does loading icon data on demand work?

Query

To load data for icons, use the following API query: [url]/{prefix}.json?icons={icons}, where:

Response is [type]IconifyJSON object.

hint: /mdi.json?icons=account-box,account-cash,account,home&pretty=1
src: api/mdi.json

Parameters

Query has one required parameter: [prop]icons, described above.

There are also optional parameters:

Error response

If icon set is not available, server returns [num]404 HTTP error.

Missing icons are added to [prop]not_found property of response.

Type

For full description of response, see [type]IconifyJSON type documentation.

You can import type from [npm]@iconify/types package.

Limitations

You cannot request data for multiple icon sets in same query. It is one query per icon set.

Number of icons per query is not limited, however be aware that browsers have limit on URL length. Iconify icon components limit URL length to 500. If URL is longer than 500 characters, API query should be split into multiple queries.

Caching

To help browser cache responses, it is recommended to have the same URLs for queries. To achive that, sort icon names alphabetically, so instead of [url]?icons=foo,bar or [url]?icons=bar,foo component always requests [url]?icons=bar,foo.

Additionally, cache responses in [prop]localStorage.

Checking for update

To check if icons were updated since last time, no need to retrieve icons again.

Use [url]/last-modified query. It returns [prop]lastModified property of icon set, which you can compare to values in cached responses.

Api

index

replacements:
  - code: '60k'
    value: '${counters.icons-short}'
  - code: '70 icon sets'
    value: '${counters.sets} icon sets'
  - code: '70 open source'
    value: '${counters.sets} open source'

Iconify API

Iconify API is an open source hosted (or self-hosted) service for developers.

What is it for?

API can be used to offer hundreds of thousands of icons in website builders or theme customisers. Host your own API, use API's search engine in custom icon picker to allow users select icons, use icon components in UI to render icons.

Hosting API

You can host your own Iconify API service.

By hosting Iconify API yourself you:

See hosting Iconify API for more details.

API is available on:

Public API

Iconify project offers public API servers, which host over 60k icons from more than 70 open source icon sets.

To improve loading times, API is hosted on multiple servers in different parts of the world. Icons are usually loaded within fraction of a second.

Public API is available at [url]https://api.iconify.design.

It is a public service, servers are free to use, but please do keep in mind that running those servers is not free. If you are using public API or API software, please consider supporting Iconify to help out with infrastructure, development and maintenance costs.

Limits

Public API has limits to prevent abuse and ensure fair usage.

Its main use case is for Iconify icon components to load icons on demand. Any other use is a bonus that should not be abused.

If you want API without limits, you can host your own Iconify API.

Queries

Iconify API can be used to render SVG, to retrieve icon data, to browse and search icons.

For full list of supported queries, their parameters and API responses see Iconify API queries documentation.

API providers

Iconify icon components can retrieve icons from multiple API servers.

This allows you to run your own API to serve only custom icons, while using public Iconify API to get data for open source icon sets.

See Iconify API providers for details.

Api

keywords

title: Icon keywords

Icon keywords

API query [url]/keywords is intended to be used for suggesting search queries.

Query

API query is [url]/keywords.

There are two variations of this query, depending on passed parameters.

You must set one of the following parameters:

If you set both [prop]prefix and [prop]keyword parameters, [prop]keyword parameter will be ignored.

Keyword

This is a very basic function. It can handle only one keyword, not multiple keywords.

Keyword requirements:

Response

Response is an object, which contains all properties passed in query and the following properties:

Examples

hint: /keywords?prefix=hom&pretty=1
src: api/keywords-hom.json
hint: /keywords?keyword=home&pretty=1
src: api/keywords-home.json

Error response

If no matches found or keyword is too short, correct response is returns with [prop]matches object being empty:

{
	"keyword": "qwerty",
	"exists": false,
	"matches": []
}

If keyword is invalid, response includes [prop]invalid property set to [bool]true:

{
	"keyword": "_",
	"invalid": true,
	"exists": false,
	"matches": []
}

If search engine is disabled, [url]/keywords route is not handled, server returns [num]404 HTTP error.

Type

Type for API response:

/**
 * Parameters for `/keywords` query
 *
 * One of `prefix` or `keyword` parameters must be set
 */
export interface APIv3KeywordsPrefixQuery {
	// Prefix to test: matches for 'foo' include 'foobar', but not 'barfoo'
	prefix: string;
}

export interface APIv3KeywordsFullQuery {
	// Keyword to test: matches for 'foo' include 'foobar' and 'barfoo'
	keyword: string;
}

export type APIv3KeywordsQuery =
	| APIv3KeywordsPrefixQuery
	| APIv3KeywordsFullQuery;

/**
 * Response for /keywords query
 *
 * Includes request + response
 */
export type APIv3KeywordsResponse = APIv3KeywordsQuery & {
	// Set to true if keyword is invalid
	invalid?: true;

	// True if partial keyword exists as is
	exists: boolean;

	// Keywords that contain partial keyword
	matches: string[];
};
Api

last-modified

title: Icon set last modification time
types:
  IconifyJSON: '../types/iconify-json.md'

Last icon set modification time

Most icon sets have last modification time in [prop]lastModified property of [type]IconifyJSON object.

If you have cached icon data, you might want to see if it was updated. You can do that by requesting icon data again, but that is inefficient.

With [url]/last-modified API query you can get [prop]lastModified value for multiple icon sets with one simple query!

Query

API query is [url]/last-modified.

Optional parameters:

Response contains [prop]lastModified object, where key is icon set prefix, value is [prop]lastModified property from that icon set.

hint: /last-modified?prefixes=mdi,mdi-light,tabler&pretty=1
src: api/last-modified.json

Error response

If requested icon sets are not found, server returns an empty object:

{
	"lastModified": {}
}

Type

export interface APIv3LastModifiedResponse {
	lastModified: Record<string, number>;
}
Api

providers

title: Iconify API Providers
types:
  APIConfig: ./providers.md#api-config
replacements:
  - code: '/2/2.0.0/'
    value: '/${svg-framework.version.major}/${svg-framework.version.full}/'
  - code: '60k'
    value: '${counters.icons-short}'
  - code: '@iconify/iconify@2'
    value: '${svg-framework.import}'
  - code: '*$/;' # get rid of auto-formatting for regexp
    value: '*$/'
  - code: 'https://github.com/iconify/iconify/issues'
    value: '${links.issues}'
  - code: 'https://github.com/iconify/iconify/sponsors'
    value: '${links.sponsor}'

Iconify API providers

If you are publishing icons, you can host your own Iconify API server that includes only your icons and give access to it to other users. Iconify icon components can retrieve icon data from multiple independent Iconify API servers.

How is it done?

Provider in icon name

Icon names in Iconify icon components have 3 parts:

All parts are separated by [str]:, provider is optional and can be skipped if empty.

Examples:

Provider naming rules are the same as for prefix and name, but with exception that it can be empty:

/^[a-z0-9]+(-[a-z0-9]+)*$/;

That regular expression means name must start with character or number, followed by mix of characters, numbers and hyphen. Other characters are not allowed.

Adding API provider

All icon components have function [func]addAPIProvider(). For SVG framework it is [func]Iconify.addAPIProvider(), for other components you need to import it from component.

Example for React component:

import { addAPIProvider } from '@iconify/react';

addAPIProvider('local', {
	// Array of host names.
	// Mutliple hosts allow redundancy: if one host is down, component will query another host.
	resources: ['http://localhost:3000'],
});

Function has 2 parameters:

For more details see addAPIProvider documentation from SVG framework.

IconifyProviders

Sometimes using function [func]addAPIProvider() is not simple. For example, if you are using SVG framework that is placed at the end of file before [tag]</body>.

There is alternative solution: assigning API providers to global variable [var]IconifyProviders before loading SVG framework. When SVG framework loads, it checks if variable exists and automatically imports all providers from it.

Format is simple: it is an object, where key is provider name, value is configuration. Example, which does the same as example above:

<script>
	IconifyProviders = {
		local: {
			resources: ['http://localhost:3000'],
		},
	};
</script>
<script src="https://code.iconify.design/2/2.0.0/iconify.min.js"></script>

Components also support it, but components are usually bundled, so you should be able to use [func]addAPIProvider() instead of polluting global variables.

Using API provider

After you add configuration for API provider, which is one simple function call, you can use icons from that API provider.

All you have to do is add provider to icon name. Provider in icon name must match first parameter to [func]addAPIProvider():

<span class="iconify" data-icon="@icons8:ios-glyphs:color-dropper"></span>
src: icon-components/common/add-api-provider.jsx

Authentication

Currently Iconify does not offer authentication options.

If you want to use API providers functionality to host premium icon sets or restrict access, you should add your own authentication logic to both API and clients. Doing that might be tricky due to lack of documentation for internal code, if you need any help, open an issue at Iconify GitHub repository.

It is on a roadmap for premium edition of Iconify API software, which should make hosting premium icon sets very easy. However, that functionality is far away due to lack of development resources. You can help by sponsoring Iconify on GitHub (click "Sponsor" button).

API Config

Type [type]APIConfig passed to [func]addAPIProvider(), is an object.

Properties:

Examples:

import { addAPIProvider } from '@iconify/svelte';

// Override default API provider with Iconify API hosted at 'https://iconify.my-project.com'
addAPIProvider('', {
	resources: ['https://iconify.my-project.com'],
});
<script>
	// Define global variable
	IconifyProviders = {
		// Empty prefix: overwrite default API provider configuration
		'': {
			// Use custom API first, use Iconify public API as backup
			resources: [
				'https://iconify.my-project.com',
				'https://api.iconify.design',
			],
			// Wait for 1 second before switching API hosts
			rotate: 1000,
		},
	};
</script>
<script src="https://code.iconify.design/2/2.0.0/iconify.min.js"></script>

Provider name

Provider name is specific to your code. It is used only to associate icon with API configuration. Actual API server has no effect on what you call provider.

That means you can change it to whatever you want. Make sure you are using the same provider id in all your code.

Api

queries

title: Iconify API Queries
types:
  IconifyIcon: '../types/iconify-icon.md'
  IconifyJSON: '../types/iconify-json.md'

Iconify API queries

This tutorial is for developers that want to create their own tools to access Iconify API.

Iconify API supports the following basic queries:

If list of icons is enabled, custom icon pickers can use the following queries to browse icons:

If search engine is enabled, icon pickers can implement search functionality using these queries:

Maintenance queries:

API versions

In code samples some queries above are marked as API v2, some as API v3.

Differences:

You can use both versions at the same time. Improved versions of old queries might be added to solve various issues, but no need to switch to new version right away, old versions will continue to be supported.

API even supports v1 queries that aren't documented and should not be used. They are supported because they can still be found in some legacy applications, such as older versions of Iconify plug-in for Sketch.

Common parameters

All queries that return JSON data have one common parameter:

Api

search

title: Searching icons
types:
  IconifyJSON: "../types/iconify-json.md"
  IconifyInfo: "../types/iconify-info.md"

Searching icons

You can search icons using [url]/search API query.

Query

API query is [url]/search.

Required parameter:

Optional parameters:

Limit and start

If your UI uses pagination, please consider saving API resources by not sending unnecessary search queries.

You can use the following logic:

Changing limit

There are limits on what you can set [prop]limit property to:

You can change limits in API code in [file]src/http/responses/search.ts.

Response

Response is a simple object with the following properties:

Examples

hint: /search?query=home&pretty=1
src: api/search-home.json
hint: /search?query=arrows-horizontal&pretty=1&limit=999
src: api/search-arrows.json

Error response

If no matches found, search returns object with no icons:

{
  "icons": [],
  "total": 0,
  "limit": 64,
  "start": 0,
  "collections": {},
  "request": {
    "query": "zzzz",
    "pretty": "1"
  }
}

If query is invalid, such as missing [prop]query parameter, server returns [num]400 HTTP error.

If search engine is disabled, [url]/search route is not handled, server returns [num]404 HTTP error.

Type

Type for API response:

import type { IconifyInfo } from "@iconify/types";

export interface APIv2SearchResponse {
  // List of icons, including prefixes
  icons: string[];

  // Number of results. If same as `limit`, more results are available
  total: number;

  // Number of results shown
  limit: number;

  // Index of first result
  start: number;

  // Info about icon sets
  collections: Record<string, IconifyInfo>;

  // Copy of request, values are string
  request: Record<keyof APIv2SearchParams, string>;
}
Api

svg

title: Rendering SVG

Rendering SVG

Iconify API can dynamically generate SVG, which can be used in HTML or CSS.

Query

API URI that generates SVG is [url]/{prefix}/{name}.svg, where:

Optional parameters:

Examples:

<img src="https://api.iconify.design/fluent-emoji-flat/alarm-clock.svg" />
/* SVG with hardcoded palette as pseudo element's content */
.test:after {
	content: url('https://api.iconify.design/fluent-emoji-flat/alarm-clock.svg?height=16');
}

/* SVG with hardcoded palette as background image */
.test-icon {
	display: inline-block;
	width: 1em;
	height: 1em;
	background-image: url('https://api.iconify.design/fluent-emoji-flat/alarm-clock.svg');
	background-repeat: no-repeat;
	background-size: 100% 100%;
}

/* Monotone SVG as mask, using currentColor for color */
.test-icon {
	display: inline-block;
	width: 1em;
	height: 1em;
	background-color: currentColor;
	-webkit-mask-image: url('https://api.iconify.design/bi/bell-fill.svg');
	mask-image: url('https://api.iconify.design/bi/bell-fill.svg');
	-webkit-mask-repeat: no-repeat;
	mask-repeat: no-repeat;
	-webkit-mask-size: 100% 100%;
	mask-size: 100% 100%;
}

See how to use icons in CSS on various ways to use icons in CSS.

Color

One downside of using SVG as external resource is it cannot inherit color from parent element. Browsers will use black instead of [key]currentColor.

There are 2 solutions to issue:

.test:after {
	content: url('https://api.iconify.design/bi/bell-fill.svg?height=16&color=%23ba3329');
}

This applies only to monotone icons. Icons that have hardcoded palette don't need [attr]color attribute.

URI cannot contain [str]#, so if you are using hexadecimal color, such as [str]#ba3329 used in example above, make sure to replace [str]# with [str]%23:

https://api.iconify.design/bi/bell-fill.svg?color=%23ba3329

Download

Parameter [str]download=1 forces browser to download generated SVG.

This can be used by websites that display icons to create links to download icon.

Box

Parameter [str]box=1 adds an empty rectangle to generated SVG that matches icon's [attr]viewBox.

It is needed when importing SVG to various UI design tools that ignore [attr]viewBox. Those tools, such as Sketch, create layer groups that automatically resize to fit content. Icons usually have empty pixels around icon, so such software crops those empty pixels and icon's group ends up being smaller than actual icon, making it harder to align it in design.

Combined with [prop]download parameter, [prop]box parameter this can be used to download SVG that will be imported correctly in software that does not support [attr]viewBox: [url]/mdi/home.svg?box=1&download=1.

Dimensions

You can also specify dimensions to SVG URL as parameters. It is pointless if you are using [prop]background-size or [prop]mask-size to resize background or mask (see examples above), but it is needed for using SVG as pseudo element's content.

To specify custom dimensions add width and/or height parameters:

https://api.iconify.design/fa-solid/home.svg?width=24&height=24

Numbers without units are treated as pixels, so [url]width=24 and [url]width=24px are identical.

If you specify only one size attribute, other attribute is calculated using width/height ratio of icon. For example, if original icon is 512x1024, setting [prop]?height=16 will result in SVG containing [attr]width="8".

There are several special keywords:

https://api.iconify.design/fa-solid/home.svg?height=unset

No need to set both width and height to special keyword, one parameter is enough (see above about width/height ratio).

Transformations

You can transform SVG generated by Iconify API, same as with placeholder elements.

Possible transformations:

Rotating icon {#rotate}

To rotate an icon, add [prop]rotate parameter. Value can be in degrees: [attr]rotate=90deg or as numbers: [attr]rotate=1 (where 1 = 90deg, 2 = 180deg, 3 = 270deg).

All transformations are done using SVG transforms, not CSS.

src: common/css-rotation.html
title: 'HTML:'
css: common/css-rotation.scss
cssTitle: 'Stylesheet:'
demo: true
demoFirst: false
demoTitle: 'Demo:'
class: css-rotation css-demo-common

Flipping icon {#flip}

To flip an icon, add [prop]flip parameter. Value is [str]horizontal or [str]vertical. If you want both, use [str]horizontal,vertical or rotate icon by 180 degrees.

All transformations are done using SVG transforms, not CSS.

src: common/css-flip.html
title: 'HTML:'
css: common/css-flip.scss
cssTitle: 'Stylesheet:'
demo: true
demoFirst: false
demoTitle: 'Demo:'
class: css-flip css-demo-common

You can use both rotation and flip on icon. Icon is flipped first, then rotated.

Api

version

title: API Version Query

API version query

API query [url]/version shows:

Region

Purpose of this query is to be able to tell which server you are connected to, but without exposing actual location of server, which can help debug error. This is used in networks when many servers are running.

For example, public Iconify API servers are running multiple servers, placed in various locations all over the world. DNS is configured to redirect visitor to the closest server using AWS Route53 latency routing. This guarantees smallest possible response time. See building budged CDN article for details.

If something goes wrong, it would be nice to know which server is causing problems, but without exposing actual IP address of server and [url]/version query solves that.

Query

API query is [url]/version.

There are no parameters.

Response

Response plain text, showing version number.

Examples

Basic response:

Iconify API version 3.0.0-beta.1

Response with [prop]STATUS_REGION=DE:

Iconify API version 3.0.0-beta.1 (DE)

Configuration

In Node.js version of API you can configure result of this API query.

Query can be enabled or disabled using environment variable [prop]ENABLE_VERSION. Possible values: [bool]true or [bool]false:

ENABLE_VERSION=false

You can also set it in [file]src/config/app.ts in [var]enableVersion property, then rebuild API.

Region value can be set using [prop]STATUS_REGION environment variable. Value is a string:

STATUS_REGION=API1

You can also set it in [file]src/config/app.ts in [var]statusRegion property, then rebuild API.

Api

build

title: Iconify API Deployment

Iconify API deployment: building API

This tutorial is a part of Iconify API deployment instructions.

This part of the tutorial explains how to build API before deploying it to a VPS instance.

Requirements

If you are using Windows, you can use Windows Subsystem for Linux.

Cloning API repository

Clone Iconify API repository.

If you are not familiar with git, you can just download repository. Click "Code" button and select "Download ZIP". Then unpack it.

Open terminal in the root of the repository.

Installing dependencies and building API

Run the following commands in the root of the repository:

npm install
npm run build

This will install all dependencies and build API.

Test

Make sure it works by running

npm run start

Wait for API to start. You can see output in terminal, when you see "API startup process complete", API is running.

Stop API process by pressing [str]Ctrl+C.

Configure

If you need to change configuration, create [file].env file in the root of the repository and add configuration variables.

See [file].env-sample for example as well as config documentation.

Next steps

Next step is to run a deployment script to set up server and deploy API.

See Iconify API deployment instructions.

Api

config

title: Iconify API Configuration

Iconify API configuration

This tutorial is a part of Iconify API installation instructions for Node.js. This part of the tutorial explains API configuration options.

There are several ways to change configuration:

If your API is already running, after changing configuration, you must restart the API. Configuration cannot be reloaded without downtime.

Env options

Options that can be changed with environment variables and their default values (you can find all of them in [file]src/config/app.ts):

Updating icons

Icons are automatically updated when the server starts.

In addition to that, API can update icon sets without restarting the server.

To enable automatic update, you must set [bash]APP_UPDATE_SECRET environment variable. Without it, update will not work.

To trigger icon sets update, open [url]/update?foo=bar, where [prop]foo is value of [bash]UPDATE_REQUIRED_PARAM, [prop]bar is value of [bash]APP_UPDATE_SECRET.

Update will not be triggered immediately, it will be run after [bash]UPDATE_THROTTLE seconds. This is done to prevent multiple checks when update is triggered several times in a row by something like GitHub hooks.

If update is triggered while an update process is already running (as in, the source was checked for update, but download is still in progress), another update check will be run after currently running update ends.

Response to [url]/update route is always the same, regardless of outcome. This is done to make it impossible to try to guess the key/value pair or even see if the route is enabled. To see the actual result, you need to check the console. Successful request and update process will be logged.

HTTP headers

By default, server sends the following HTTP headers:

See how to change HTTP headers in API for more details.

Memory management

API does not store all loaded icons in memory. Instead, it splits icon sets into smaller chunks, stores them in cache and loads those chunks from cache when needed. After loading a chunk from cache, it is stored in memory for a while. This way, the most used icons are in memory, rarely used icons are not using memory.

There are two configuration variables that deal with that:

All properties in those config objects can be changed via environment variables. Convert property to underscore-separated upper case, add [str]SPLIT_ prefix for [var]splitIconSetConfig, [str]STORAGE_ prefix for [var]storageConfig.

Config values that you might want to change, as environment variables:

If you want to always keep icon data in memory, set [bash]SPLIT_CHUNK_SIZE=0 and [bash]STORAGE_MAX_COUNT=0. This is useful to make responses as fast as possible if your API instance does not serve hundreds of thousands of icons.

Api

deployment

title: Iconify API Deployment

Iconify API deployment

This tutorial explains how to deploy an API instance on your VPS.

Using a simple VPS is an easy and cheap way to host your own API instance. Depending on hosting provider and memory requirements, it costs from $5 to $25 per month.

How it works

Deployment script will handle everything: configuring server, uploading files and starting API server.

Domain requirements

For simplicity, you need a domain hosted at Cloudflare or similar service.

API is hosted on port 80. It does not handle TSL (HTTPS) or caching, so Cloudflare takes care of that.

Hosting requirements

Deployment script is designed to work only on Ubuntu Linux, so make sure your VPS instance is running Ubuntu.

Deployment script was fully tested only with Vultr hosting.

Vultr is a reasonably priced and reliable hosting provider, used to host Iconify websites for many years without issues.

It may work with other hosting services, but currently tested only on Vultr.

Process

Short version of the process:

  1. Create a new VPS instance on Vultr with Ubuntu Linux.
  2. Clone Iconify API repository to your local machine, install dependencies, configure API if needed, run build script.
  3. Run deployment script with instance IP address to deploy the API.
  4. Configure your (sub)domain at Cloudflare to point to the server IP.

Each step is explained below.

VPS instance

First, you need to create a VPS (virtual private server) instance.

See VPS setup instructions for details.

Make sure authentication for root user is done with SSH key, not a password.

Building API

To run API, you first need to build it.

Clone API repository, install dependencies, build it and configure it if needed.

See build instructions for details.

SSH key

Configure API by editing [file].env file.

Make sure you add your SSH key file location and passphrase to [file].env file, it will be used to deploy API to VPS instance.

When files are uploaded, those keys are removed from [file].env file, so they are not stored on server.

Run deployment script

When ready, run deployment script with instance IP address to deploy the API:

node lib/setup-server.js --ip <instance-ip>

Script will:

After script is finished, wait 2-3 minutes for server to start. It will download all icon sets and cache them, which may take a while.

Test that API is working by opening [url]http://<instance-ip>/version in your browser or any other valid API endpoint.

Updating files

Additionally, there is a script to update files on server without reinstalling Node.js and PM2:

node lib/upload.js --ip <instance-ip>

This script will upload files and restart API server.

Configure domain

When done, configure your domain to point to the server IP and configure Cloudflare to handle TSL and caching.

To do that, go to Cloudflare dashboard, select your domain, go to DNS settings and add an A record with your server IP.

Conclusion

This is it!

API is now running on your VPS instance and ready to use.

To make sure API is always working, deployment script sets up PM2 to automatically restart API server if it crashes or server is restarted.

If you need to change configuration or update files, you can do that by editing files and running upload script.

Api

headers

title: HTTP Headers in Iconify API

HTTP headers in API

This tutorial is a part of Iconify API installation instructions for Node.js. This part of the tutorial explains how to change HTTP headers that API server sends to visitors.

By default, server sends the following HTTP headers:

To change headers, edit [prop]httpHeaders variable in [file]src/config/app.ts, then rebuild script:

If you prefer to use reverse proxy to send all extra headers, remove all unnecessary headers in the file mentioned above and change the configuration in reverse proxy.

Configuring CORS in Apache {#cors-apache}

If you are using Apache as reverse proxy, you can disable CORS in API and enable it in Apache.

To enable CORS in Apache, add this to Apache configuration:

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "GET, OPTIONS"
Header always set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding"
Header always set Access-Control-Max-Age "86400"
Header always set Cross-Origin-Resource-Policy "cross-origin"

Configuring CORS in NGINX {#cors-nginx}

If you are using NGINX as a reverse proxy, you can disable CORS in API and enable it in NGINX.

To enable CORS in NGINX, add this to NGINX configuration under [prop]http -> [prop]server -> [prop]location:

if ($request_method = 'POST') {
   add_header 'Access-Control-Allow-Origin' '*';
   add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
   add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
   add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
   add_header 'Cross-Origin-Resource-Policy' 'cross-origin';
}
if ($request_method = 'GET') {
   add_header 'Access-Control-Allow-Origin' '*';
   add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
   add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
   add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
   add_header 'Cross-Origin-Resource-Policy' 'cross-origin';
}
Api

Hosting Iconify API

This documentation is for the Node.js version of Iconify API.

To install API, first clone or download Iconify API from GitHub: https://github.com/iconify/api.

How to use it

First, you need to install NPM dependencies and run build script:

npm install
npm run build

Then you can start server:

npm run start

By default, server will:

You can customise API to:

Port and HTTPS

Run API on obscure port, hidden from the outside world with firewall rules, use nginx as reverse proxy.

HTTPS is not supported. It is a very resource intensive process, better handled by a dedicated solution such as nginx. Use nginx to run as HTTP and HTTPS server, forward queries to API HTTP server on hidden port such as default port [num]3000.

Configuration

There are several ways to change configuration:

See Iconify API configuration for details.

Starting server

To start server, run

npm run start

PM2

To make sure API runs without interruption, use pm2 or similar Node.js process manager to run application.

It will automatically restart API if something goes wrong and will automatically start API if the server is restarted. Sometimes host server might restart for whatever reason, this will make sure the API is always running.

Api

reverse-proxy

title: Reverse Proxy for Iconify API

Reverse proxy for Iconify API

This tutorial is a part of Iconify API installation instructions.

It explains how to configure reverse proxy for hosting Node.js version of Iconify API in a custom hosting environment.

Why is it needed?

What is reverse proxy and why is it needed?

Running Node.js applications on port [num]3000 without reverse proxy is fine for localhost development, but usually it is not fine for production.

In a production environment, you want stability and HTTPS support. That should be delegated to a reverse proxy. Reverse proxy allows you to add HTTPS support, add security features such as rate limiting.

Reverse proxy handles HTTP and HTTPS requests, forwards them to Node.js application and returns response to customer. It is useful if you want to:

CloudFlare

You can avoid this by using service like CloudFlare. It handles all HTTPS requests and deals with security stuff.

If you are using such service, you can run API on port 80 and forget about reverse proxy.

Configuration

Before configuring reverse proxy, you need to make sure Iconify API runs on a port hidden from the outside world.

Default port is [num]3000. See API configuration for details.

Apache 2.4 {#apache}

This section explains how to create a reverse proxy with Apache 2.4.

In [file]httpd.conf you need to uncomment these 2 lines to enable [prop]mod_proxy:

LoadModule proxy_module libexec/apache2/mod_proxy.so
LoadModule proxy_http_module libexec/apache2/mod_proxy_http.so

Then you can add [prop]mod_proxy to virtual host like this:

<VirtualHost *>
    ServerName api.yourdomain.com
    ProxyPass "/" "http://localhost:3000/"
    ProxyPassReverse "/" "http://localhost:3000/"
</VirtualHost>

This configuration will allow you to access API at [url]http://api.yourdomain.com/.

Here is an alternative solution, that you can add to your existing [prop]VirtualHost directive that allows you to run API on subdirectory:

<VirtualHost *>
    ServerName yourdomain.com
    ServerAdmin noreply@sourceforge.net
    DocumentRoot "/home/iconify/htdocs"
    ProxyPass "/api/" "http://localhost:3000/"
    ProxyPassReverse "/api/" "http://localhost:3000/"
</VirtualHost>

This solution will allow you to access API at [url]http://yourdomain.com/api/.

NGINX

This section explains how to create a reverse proxy with NGINX.

Open [file]nginx.conf, find section with your domain. It is under [prop]http -> [prop]server -> [prop]location:

http {
    # some stuff here
    server {
        listen 80;
        server_name api.yourdomain.com;

        # some stuff here
        location / {
            root   html;
            index  index.html index.htm;
        }
        # some stuff here
    }
    # some stuff here
}

Replace contents of [prop]location with this:

http {
    # some stuff here
    server {
        listen 80;
        server_name api.yourdomain.com;

        # some stuff here
        location / {
            proxy_pass http://127.0.0.1:3000;
            proxy_http_version 1.1;
            proxy_buffering on;
            proxy_buffers 16 1024k;
        }
        # some stuff here
    }
    # some stuff here
}

You will need to do this change twice: once for HTTP server, once for HTTPS server. In your [file]nginx.conf look for second [prop]server section with SSL settings that is configured to listen on port [num]443 and apply exactly the same changes.

This configuration will allow you to access API at [url]http://api.yourdomain.com/.

If you want to host API in subdirectory, instead of editing the default location block, add custom location:

http {
    # some stuff here
    server {
        listen 80;
        server_name yourdomain.com;

        # some stuff here
        location / {
            # some stuff here
        }
        location /api/ {
            proxy_pass http://127.0.0.1:3000;
            proxy_http_version 1.1;
            proxy_buffering on;
            proxy_buffers 16 1024k;
        }
        # some stuff here
    }
    # some stuff here
}

This solution will allow you to access API at [url]http://yourdomain.com/api/.

Resolving POST errors in NGINX {#post-nginx}

If you are using GitHub web hooks to synchronize icon sets, you might run into error [num]500. It is very likely to happen if you have fresh NGINX installation.

That error is likely to be caused by NGINX having wrong permissions. Run this to fix it:

sudo chmod +x /var/lib/nginx -R
Api

vps

title: Iconify API Deployment

Iconify API deployment: setting up VPS instance

This tutorial is a part of Iconify API deployment instructions.

This part of the tutorial explains how to set up a VPS instance for the API.

SSH key

First, you need to create SSH key pair on your local machine.

This is used to log in to server without password.

GitHub has an excellent guide.

This will create two files:

File names might be different, depending on your configuration. Account for that in the next steps.

This documentation assumes you are using MacOS or Linux. If you are using Windows, you can use Windows Subsystem for Linux to run Linux commands.

Vultr account

This tutorial assumes you are using Vultr hosting provider.

Adding SSH key to Vultr

Click "Orchestration" in menu on the left, then "SSH Keys".

Click "Add SSH Key", give it a name and copy contents of [file]~/.ssh/id_rsa.pub to "SSH Key" field.

Make sure you copy public key, not private key!

Adding SSH key to Vultr

Creating a VPS instance

Click "Compute", then "Instances" in menu on the left.

Navigating to instances

Click "Create Instance" to create a new instance.

Select "Shared CPU" to see cheapest options. This is more than enough to run API.

Instance size is all about memory usage.

Memory usage depends on:

If you want to host all icon sets, disable memory management for best performance, you will need at least 2GB RAM.

Select "High Frequency" on left side, those servers are optimal for API, then select instance based on required memory.

Number of CPU cores is not important, API is single-threaded, so it will use only one core.

Selecting VPS instance

Disable automatic backups, as they are not needed for this project.

In the unlikely event of failure, you can always create a new instance and deploy API again.

Disable backups

Select region where you want API to be deployed, click "Configure".

Make sure Ubuntu is selected.

Select Ubuntu

In "Server Settings" in "SSH Keys" section, select SSH key you created and uploaded earlier.

Select Ubuntu

For server hostname and label, you can use anything you want, for example, "iconify" or "api".

Click "Deploy" to create instance.

Wait for instance to be created. It might take a few minutes.

Next steps

Next step is to build API, then run a deployment script to set up server and deploy API.

See Iconify API deployment instructions.

Articles

Articles

index

title: Iconify blog

Iconify blog

Blog below contains major updates, migration guides and helpful articles related to Iconify project.

Iconify stuff

Animated icons

How to work with animated SVG:

Migration guides

Migration guides for major releases:

Articles

vendor-lock-in

title: Vendor lock-in and icons
replacements:
  - code: "60k"
    value: "${counters.icons-short}"
  - code: "70 icon sets"
    value: "${counters.sets} icon sets"

Vendor lock-in

What is vendor lock-in?

Vendor lock-in is when someone is essentially forced to continue using a product or service regardless of quality, because switching away from that product or service is not practical.

Icon sets

Most icon sets have their own icon components or fonts with stylesheets.

When using those components or fonts, you no longer have freedom to choose icons, you are only limited to icons provided by your chosen vendor.

Issues:

You are forced to choose bad icons or spend a lot of time.

Vendor lock-in with customisable software

Worst case of vendor lock-in, is when you are working with customisable software, who's authors made a choice to use a specific icon set or icon font. Very common cases are popular forum and blogging software packages.

Forums and blogging software have:

Unless you are designing theme only for yourself, as a theme designer you need to make sure it works with third party plug-ins. Third party plug-ins are designed to work with whatever default theme software package offers. So, even if you want to change icon set in your theme, you still need to keep default icon set or third party plugins might not work.

This very specific vendor lock-in is one of reasons why Iconify was created. After years of frustration of working with one very popular icon font, I wanted to find a solution to vendor lock-in for forum software, but at that moment there were none. See about Iconify.

Iconify

When using Iconify, doesn't it lock-in to Iconify?

Sort of, but it is a technology lock-in, not vendor lock-in and there are huge differences. See below.

Iconify was designed to be as flexible as possible, the only way you can get more freedom is directly embed SVG files one by one, without any specific icon set. Working with SVG is not easy for most developers and it is very time consuming.

Icons

One big difference is choice of icons. When using any icon set, you are limited to that icon set.

When using Iconify, you can use over 70 icon sets.

Custom icons

Most icon components support custom icon loaders, making it easy to use Iconify with custom icons.

Iconify also offers open source tools for cleaning up and optimising icons. Same tools that are used by Iconify scripts to keep icon sets up to date.

API

Some icon components get icon data from Iconify API. Doesn't that lock-in users to third party services?

No.

API is open source, you can host your own API, where you have full control over available icon sets and over servers.

Icon components can be easily configured to use your Iconify API servers. You can also build custom version of icon components that have your servers pre-configured.

Everything is open source!

Components

Icon data is available for everyone. You are not forced to use Iconify icon components.

Furthermore, third party icon components are very welcome... as long as it is high quality and maintained!

Freedom to choose

With Iconify you are free to do whatever you want.

Theme designers can choose from hundreds of thousands of icons or add their own icons, without worrying about compatibility with third party plug-ins.

Articles

index

title: How to add icon set to Iconify

How to add icon set to Iconify

If you have created an icon set, please consider sharing it with Iconify community.

Benefits

What are the benefits of publishing an icon set to Iconify?

Adding icon set

To add an icon set to Iconify, all you need to is open an issue on Iconify icon sets repository on GitHub.

In opened issue you need to post:

Icon set source

Icon sets are automatically updated several times a week. In order to update icon set, icons must be published and maintained by developer on one of the following sources:

Updates must be automated, so manually downloading icons from a third party website is not an option.

Open source

All icon sets must be open source and have a valid open source license.

If you are not sure about licenses, check out various icon sets. Click any icon set, it will show license and link to license text.

See Open Source Initiative for more licenses.

Bad icon sets

Not all icon sets are the same. There are good and bad icon sets. Bad icon sets are not accepted.

Most common reasons:

Design tips

If you are new to icon design, Google Material Icons website has excellent guidelines for designing icons.

Those guidelines are specific to material design, but the same principles apply to most icons. Even though icons are vector images, displays are pixel devices and icon edges are blurred if shape is not aligned to the edge of a pixel. Icon sets that follow a specific grid, have padding, shapes aligned to pixel edges, are the best looking icon sets.

Articles

cleanup

title: Cleaning up SVG code
functions:
  cleanupSVG: '/docs/libraries/tools/icon/cleanup.md'

Cleaning up SVG code

This article is part of SVG clean up article.

When a designer exports icon from an editor, often SVG contains a lot of extra code that is not needed to display an icon.

Bad icon example {#example}

The following SVG was generated with popular Inkscape software:

src: articles/el-cloud.svg

That code contains a lot of useless junk. If it is not used to display an icon, it is useless.

This is what is left of it after clean up:

src: articles/el-cloud.cleanup.svg

Icon is not yet finalised. It still requires optimisation.

If you think the code above contains just a little bit of useless tags, so it is not a big deal, it was a short example. There are icons in some icon sets with tens of kilobytes of junk data.

Process

Clean up process does not optimise the icon. It only does the following:

It is done with the [func]cleanupSVG() function from Iconify Tools.

Optimisation is done later, after parsing palette.

Articles

index

title: Cleaning up icons
types:
  IconifyJSON: '/docs/types/iconify-json.md'
functions:
  importDirectory: '/docs/libraries/tools/import/directory.md'
  forEach: '/docs/libraries/tools/icon-set/for-each.md'

Cleaning up icons

All icon sets available with Iconify pass validation and clean up process.

Why is it needed? SVG is not like other images, it can contain a lot of things, making it hard to work with.

Often icons contain a lot of useless code (especially when exported from old software).

Icons can even contain malicious code, such as scripts, event listeners and links to external resources.

When working with monotone icons (icons that have only one color, which supposed to be changeable), some icons use [attr]fill, some [attr]stroke, some rely on system default colors, some use [prop]black color, some use seemingly random colors.

All the tools you need are available in Iconify Tools package.

Process

Clean up process is done in 3 steps:

Validation and initial clean up {#cleanup}

First part is code validation and initial clean up.

When a designer exports an icon from an editor, often SVG contains a lot of extra code that is not needed to display an icon.

Icons can also contain dangerous elements, such as scripts or external resources. Icons are validated to make sure they do not contain anything other than vector shapes.

See example of bad code and explanation of how SVG validation works.

Palette changes {#palette}

After initial clean up and validation, the icon palette is changed.

For monotone icons, color is changed to [prop]currentColor to make sure the icon follows text color. This way it is easy to change color for any icon, regardless if the icon uses [prop]fill or [prop]stroke.

For icons with a hardcoded palette, the parser checks that the icon does not use system default colors or [prop]currentColor.

See article explaining palette changes.

Optimisation {#optimisation}

Last step is optimisation. It reduces icon size by removing unnecessary code and optimising paths.

See a very short article explaining icon optimisation.

Code

Want to try it with your icons? All functions you need are available in Iconify Tools.

Below are several examples.

Parsing one monotone icon

This code sample parses one monotone icon. Icon uses black color, which is replaced with [prop]currentColor, shapes with white color are removed.

Icon is loaded from one file, output is stored in another file.

src: libraries/tools/examples/cleanup-one-icon.ts

Parsing an entire icon set

This code sample parses an entire icon set and returns icon set in [type]IconifyJSON format.

It is similar to the example above, but uses [func]importDirectory() to import all SVG files in a directory, then stores the result in a JSON file. Each icon is parsed in asynchronous [func]forEach() callback.

src: libraries/tools/examples/cleanup-directory.ts
Articles

optimise

title: Optimising icon code
functions:
  deOptimisePaths: '/docs/libraries/tools/icon/paths.md'
  runSVGO: '/docs/libraries/tools/icon/svgo.md'

Optimising icon

This article is part of SVG clean up article.

After initial clean up and validation, changing icon palette, the icon is optimised.

Optimisation is done by SVGO. Not much to write about it, you can try SVGO optimisation yourself using SVGOMG project.

Code

Optimisation is done using [func]runSVGO() function from Iconify Tools, followed by [func]deOptimisePaths() to make sure icons are usable everywhere.

Articles

palette

title: Changing icon palette
functions:
  parseColors: '/docs/libraries/tools/icon/colors.md'

Changing icon palette

This article is part of SVG clean up article.

After initial clean up and validation, the icon palette is changed.

There can only be two types of icons:

Icons with palette {#palette}

Some icons have hardcoded palette:

include articles/icon-palette

Colors of these icons cannot be easily changed with a stylesheet.

When such icons are cleaned up, the parser verifies that the icon does not follow system default color (black color for [attr]fill) and does not contain [prop]currentColor.

Monotone icons {#monotone}

Most icons are monotone. They have only one color, which can be changed.

include articles/icon-monotone

When parsing monotone icons, color is changed to [prop]currentColor to make sure the icon follows text color. This way it is easy to change color for any icon, regardless if icon uses [prop]fill or [prop]stroke:

svg {
	color: red;
}

Parsing such icons is not easy. When icons are exported from editors, color is not set to [prop]currentColor. Usually monotone icons come with shapes that either use black color or system default color.

Sometimes icons also include white background, which needs to be removed. Parser cleans it up too.

System color

Usually, icons that use [prop]fill, do not have any colors:

<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
    <path d="M4 17h2.697L14 21.868V2.132L6.697 7H4c-1.103 0-2 .897-2 2v6c0 1.103.897 2 2 2z"/>
</svg>

Color in those icons is intended to be changed by changing [prop]fill property:

svg {
	fill: red;
}

Problem is, many icons use [prop]stroke instead of [prop]fill, so this approach does not apply to many icon sets, therefore it cannot be used.

Parser modifies those icons by setting [prop]fill to [prop]currentColor on elements that use system default [prop]fill:

<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
    <path d="M4 17h2.697L14 21.868V2.132L6.697 7H4c-1.103 0-2 .897-2 2v6c0 1.103.897 2 2 2z" fill="currentColor"/>
</svg>

Custom color

Usually when you export an icon from editor, it uses whatever color you were using when designing it, usually black:

<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
    <path d="M5 12H19" fill="none" stroke="black" stroke-width="2" stroke-linecap="round"/>
</svg>

Parser changes it to [prop]currentColor:

<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
    <path d="M5 12H19" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
</svg>

Result

After changes, all shapes that use [prop]fill have [prop]fill set to [prop]currentColor, all shapes that use [prop]stroke have [prop]stroke set to [prop]currentColor, which means icon uses same color as text and can be styled as text:

svg {
	color: red;
}

Mixing palette and currentColor

Icons that mix [prop]currentColor and hardcoded palette are not allowed.

Such icons cannot be used in a stylesheet. In stylesheet monotone icons are used as masks, icons with palette are used as background. When the icon component detects [prop]currentColor in the icon, it assumes that the icon is monotone and uses it as a mask, displaying it incorrectly.

Also such icons assume that [prop]currentColor is either light or dark or cannot be a certain hue. It is just a bad design.

Code

Palette is parsed using the [func]parseColors() function from Iconify Tools.

Articles

validate

title: Validating SVG
functions:
  cleanupSVG: '/docs/libraries/tools/icon/cleanup.md'

Validating SVG

This article is part of SVG clean up article.

SVG can contain a lot of stuff that might be dangerous: scripts and external resources.

Style

Global [tag]style and inline [attr]style are converted to attributes.

Style complicates the process of analysing an icon structure, which is needed to later get rid of unused elements and parse the palette, so style should go. If style is too complex to parse or style overrides attribute, an exception is thrown.

Bad tags

During clean up, the icon is also checked for bad stuff.

Validation is very strict and opinionated.

Things that will cause validation to fail (function will throw an exception):

src: articles/script.svg
src: articles/image.svg

Removed tags

Clean up function has a list of all allowed SVG tags and their attributes.

If an unknown tag is encountered, this happens:

Attributes

Clean up function also checks each attribute on each element.

All attributes that do not affect icon rendering are removed.

If an event listener is found, the function throws an exception.

[attr]class attribute is allowed.

Inline [attr]style is converted to attributes (before parsing other attributes).

Text and fonts

All text tags are not allowed.

Why? Because different operating systems have different fonts, it will cause the icon to render differently.

This rule cannot be disabled.

src: articles/text.svg

Raster images

Sometimes raster images are used by icons for various purposes, usually masks or masked content.

They are not allowed. Why?

Clean up

Validation is done during clean up process.

It is done with the [func]cleanupSVG() function from Iconify Tools.

Articles

icon-v3

title: April 2025 Iconify icon components migration guide

Icon components migration guide

The following migration guide applies to:

New major versions of all components mentioned above was released in April 2025.

This was a breaking change, this migration guide should help you change your code.

Changes

Update introduces the following changes:

There are more changes for Vue and Svelte components, see below.

iconExists removal

Do not worry, function is not gone. It was renamed to [func]iconLoaded().

Reason for renaming function is really bad name. It was internal name in initial versions of component, used inside storage module. It checks if icon exists in storage, which makes sense within storage. However, when exported from component, function no longer storage specific, so it gave impression that it can be used to check if icon exists in Iconify API.

To avoid confusion, later function was renamed to [func]iconLoaded(), but old name [func]iconExists() was supported for backwards compatibility.

New major version is a good time to get rid of it.

Migration is as simple as it can get: change function name in your code.

Cache functions

Caching in storage is no longer available.

To migrate, simply remove usages of those functions.

See [/news/2025.md#components-storage](January 2025 news) for detailed explanation of why these functions were removed.

Vue changes

Vue component has been rewritten with Vue's Composition API. It does not change behavior, but now you can remove Options API from bundle if other components do not use it.

Other changes:

onLoad

Callback [prop]onLoad in Vue component has been replaced with [prop]load event.

Old code:

<template>
  <Icon icon="mdi:home" :onLoad="(icon) => console.log('Loaded', icon)" />
</template>

New code:

<template>
  <Icon icon="mdi:home" @load="(icon) => console.log('Loaded', icon)" />
</template>

Svelte

Svelte component has been rewritten using Svelte 5 runes.

If you are still using Svelte 4 or older version, new Svelte component will not work for you.

You need to use version 5 of component:

npm install --save-dev @iconify/svelte@4

or use a web component.

onLoad

Event [prop]on:load in Svelte component has been replaced with [prop]onload callback.

Old code:

<Icon icon="mdi:home" on:load={(event) => console.log('Loaded', event.detail.icon)} />

New code:

<Icon icon="mdi:home" onload={(icon) => console.log('Loaded', icon)} />
Articles

index

title: Iconify migration guides

Iconify migration guides

Migration guides for major releases.

2025

2024

Articles

index

title: "SVG animations level 2 spec: common issues and solutions"

Solving SVG animation spec issues

There are various ways to animate icons:

This article is about the last method: animating icons using SVG animations level 2 spec.

SMIL?

No, it is not the old deprecated SMIL animations.

It is a modern spec, though it is based on SMIL. Currenly it is supported by all modern browsers.

Sample

So what do SVG animations look like?

src: articles/animations/image-twotone.svg
demo: true
demoFirst: false
class: restart-animation

This example uses [tag]animate tag to change attributes of parent elements over time. It changes [prop]stroke-dashoffset to animate stroke, so it looks like icon is being drawn and [attr]fill-opacity to fade in filled elements.

No CSS, no JavaScript, no external dependencies.

See [tag]animate documentation on MDN and SVG animations level 2 spec for more examples, other related tags, attributes.

Timing

Unfortunately, SVG animations spec has one major downside: animation timing is very tricky to work with.

What exactly does that mean?

There are 2 ways to render SVGs:

Both have different problems with animation timing.

Inline SVG

When using inline [tag]svg, animations cannot start until document is ready.

It might seem like a small thing, but animations not rendering quickly enough can cause bad user experience.

This issue can be caused by small things, such as statistics script failing to load or ad code loading slowly. If at least one server that page is loading resources from is unreachable, it might break all animated SVGs on page. Async and defer attributes do not help. Issue can even be caused by script in an iframe.

Solution? {#solution-svg}

There is none.

If you website has a lot of external dependencies that might delay animation, do not use inline SVG for animated icons.

SVG as URL

When using icon as URL, you cannot control animation timing at all.

Animation always starts the first time icon is rendered. There is absolutely no way to control that.

Solution? {#solution-css}

The only solution is to generate unique URL for icon each time you need to restart animation.

The easiest way to achieve it is to add a basic HTML comment to icon content, like this:

.test-icon {
  --svg: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cg fill='none' stroke='currentColor' stroke-linecap='round' stroke-linejoin='round' stroke-width='2'%3E%3Cpath stroke-dasharray='20' stroke-dashoffset='20' d='M3 12h17.5'%3E%3Canimate fill='freeze' attributeName='stroke-dashoffset' dur='0.2s' values='20;0' /%3E%3C/path%3E%3Cpath stroke-dasharray='12' stroke-dashoffset='12' d='M21 12l-7 7M21 12l-7 -7'%3E%3Canimate fill='freeze' attributeName='stroke-dashoffset' begin='0.2s' dur='0.2s' values='12;0' /%3E%3C/path%3E%3C/g%3E%3C!-- 1234567890 --%3E%3C/svg%3E");
  width: 1em;
  height: 1em;
  background-color: currentcolor;
  mask-image: var(--svg);
  mask-repeat: no-repeat;
  mask-size: 100% 100%;
}

Notice [str]%3C!-- 1234567890 --%3E near end of URL. This is a simple comment with a number to break browser's cache.

Unfortunately, this solution requires JavaScript. It can be used as inline CSS, it cannot be used in CSS file.

Iconify web component

A simple solution to issues is to use Iconify icon web component web component.

Iconify icon web component renders animated icons as background or mask images and implements randomised URL workaround.

Additionally, it renders icons only when icon is visible. This means CPU is not wasted on animating invisible icons.

Conclusion

SVG animations spec is promising, but it is hard to use.

CSS animations are a better choice, but at the time of writing this, CSS animations are not fully supported yet by all major browsers (see update below). More specifically, only basic animations like [prop]stroke-dashoffset work, animating other attributes is not supported (see update below). This makes animating icons in CSS impossible beyond very basic animations.

Update

Update for CSS animations: April 2025.

In 2024 all major browsers added support for animating majority of SVG attributes in CSS.

The only exception is [prop]d attribute in path, which is actually the most important attribute. Safari 18.4 does not support animating or changing [prop]d in CSS, but it is supported in Safari TP, so hopefully support will land in Safari 18.5.

index

title: Iconify Documentation
replacements:
  - code: "60k"
    value: "${counters.icons-short}"
  - code: "60,000"
    value: "${counters.icons}"
  - code: "80 icon sets"
    value: "${counters.sets} icon sets"
  - code: "80 open source"
    value: "${counters.sets} open source"

Iconify documentation

Iconify is a set of tools for developers and designers, created to make it easy to work with different icon sets in a consistent way.

It includes:

How to use icons

Iconify ecosystem offers many ways to use icons, for both coders and designers.

To use icons in HTML documents, there are several viable options:

include usage/options/html

For designers, Iconify ecosystem offers several ways to easily import icons in various design tools:

include usage/options/design

You can browse all available icons and copy code or SVG on the following websites:

include usage/options/websites

Find icon you want, select it, copy code sample or SVG to clipboard, paste it in your project.

See how to use icons for more details.

Icons data

Unlike other projects, Iconify is not a dump of SVG files.

Icons pass strict validation, clean up and optimisation process. Icons are automatically kept up to date.

If you want to use icons with your own components, icon data is available in easy to use format.

In the icons section of documentation you will find:

Libraries

Iconify offers several packages to work with icons.

All packages are JavaScript only. However, formats are rather easy to understand, types are documented, so you can port code to whatever language you are using.

There are 3 main packages:

Types

Before using any tools, you need to understand data structures used in Iconify ecosystem.

See Iconify types documentation.

Utils

Iconify Utils contains reusable functions for:

as well as many other helper functions.

This package is designed to work in any environment. It is used by all Iconify packages, including icon components, API, plugins.

Tools

Iconify Tools is designed to import, export and process icon data.

It is used to maintain available open source icon sets.

This package is designed to work only in Node.js. It is not usable in the browser.

API

Iconify API is an open source hosted (or self-hosted) service, indented for developers. It is used to:

Design

Design

index

title: Iconify for Designers

Iconify for designers

For designers, Iconify ecosystem offers several ways to easily import icons in various design tools.

Available options:

Browse icons

You can browse and search more than 60k open source icons at one of the following websites:

Find icon you want, select it, copy SVG to clipboard, paste it to your favorite design tool.

Possible issues:

Design

index

title: Iconify for Figma
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "70+"
    value: "${counters.sets}+"

Iconify for Figma

With the Iconify plugin for Figma you can import over 60,000 vector icons to Figma.

It is completely free!

Unlike other plugins that offer many icons, but require payment to use SVG, Iconify always imports icons as SVG. Iconify project is open source and offers only open source icon sets.

Plugin remembers the last page you have visited, making it easy to continue searching or browsing icons.

For visitors that have small monitors, the plugin offers compact mode. Button to toggle compact mode is in the top right corner of the plugin window.

Installation

You can install Iconify for Figma from Iconify plugin page.

Usage

In Figma menu select [str]Plugins, then select [str]Iconify.

Browse or search icons, select any icon, click [str]Import Icon button or drag icon to the Figma document.

Detailed instructions

After opening the plugin, you will see the main page:

Iconify for Figma: main page

Click any icon set or search icons.

When you click an icon set, the plugin will show you all icons in that icon set. You can filter icons by categories (if the current icon set has them), search icons.

To show more icons, simply scroll the icons list.

Iconify for Figma: icon set

You can also search all icon sets for icons. For example, search for "gear":

Iconify for Figma: icon search results

The plugin will show you all icons that match your keyword.

When you hover any icon, you will see a button to show more information.

If you hover it, you will see the icon name. If you click it, you will see:

You can import icon by:

Advanced import

When you select an icon, it will appear in page footer with options:

Iconify for Figma: icon code

For icons that do not have a hardcoded palette, color picker is available, showing recently used colors and available color styles:

Iconify for Figma: color picker

Compact mode

If you have limited window space available, you can make the plugin window even smaller.

Click the compact window button in the top right corner and the plugin window will become much smaller:

Iconify for Figma: compact mode

Support and feedback

Feedback is welcome.

See [str]feedback page in the plugin or visit support page on website.

Design

update-2024-attempt2

title: Iconify for Figma update

What's new in Iconify for Figma

Welcome to the new Iconify plugin for Figma.

In 2024, the plugin has been completely rewritten. The new version has nothing in common with the old version, so this is a rather radical change, which requires a tutorial.

This is a second attempt at rewrite. First attempt failed miserably because of bad UX. New version has been redesigned to vastly improve UX.

New UI

The first change you'll notice immediately is the new layout.

Plugin is designed to fit as much content as possible in the smallest possible space.

Iconify for Figma: main page

You can make it even smaller by clicking the button in navigation to toggle compact width.

Iconify for Figma: compact mode

Due to limited space, the plugin uses tooltips to show additional information.

License information

One of the biggest changes is advanced license information.

Even though all icon sets are open source, not all open source licenses are equal. Some ask for attribution, some prevent commercial use.

The new plugin shows attribution requirement and commercial use limitation in various places:

Iconify for Figma: search results

Additionally, you can filter icon sets and search results by license (see below).

Advanced filters

There are many icon sets, finding an icon set that you want might be a challenge.

The new version of the plugin has advanced filters to help you find icon sets.

You can filter icon sets by:

Iconify for Figma: advanced filters

You can also use filter input to filter icon sets by all of the above, plus author name (case insensitive):

Iconify for Figma: advanced filters

Favorite icon sets

You can now mark icon sets as favorite.

This can be done by clicking the star button when viewing an icon set page or icon set tooltip.

Iconify for Figma: star an icon set

When browsing the icon sets list, if you have marked some icon sets as favorite, you will see the new option to browse only favorite icon sets.

Iconify for Figma: favorite icon sets

All lists (favorite and recent icon sets, recent icons) are considered to be private data (stored in Figma) and can be cleared.

Custom lists

You can also create custom lists of icon sets by clicking a button next to star button shown in screenshots above.

Scrollable icons

Previous versions of the plugin used pagination to show many icons. You needed to click page buttons to show more icons, which was not convenient.

The new version of the plugin has completely redesigned icons view:

Iconify for Figma: icon set

Color styles

When importing icons, you can now pick color styles in color picker.

Due to Figma plugin system limitation, color picker might not show all color styles.

The plugin has access to:

So if you have color styles shared from another document, the plugin might not see them. To add them to color picker, you need to select any layer that uses that color style.

Iconify for Figma: color picker

Solid colors only

Note that the plugin supports only color styles that have one solid color.

Gradients, patterns, colors with opacity are not supported.

Replacing icons

If you have selected a layer that contains icon, which was previously imported with plugin, you will see an option to replace that icon (icon with left/right arrows on screenshot below).

Option to replace icon already existed in the previous version of the plugin, but now it has been redesigned.

When replacing an icon, new icon will keep old icon's:

Iconify for Figma: replacing icon

It is available in multiple places:

Animated icons

Unfortunately, Figma does not support SVG animations.

But it does not mean you cannot use animated icons in your work.

The new version of the plugin allows you to import animated icons to Figma. It will parse animations, remove animations and import static icon without animations.

This allows you to use animated icon in the design.

In production code, you can copy SVG with full animations from the Iconify website or use Iconify icon components.

Iconify for Figma: animated icons

Removed functions

Not all functions from the old version made it to the new version:

Feedback

Feedback is welcome.

See [str]feedback page in the plugin or visit support page on website.

Design

update-2024

title: Iconify for Figma update

What's new in Iconify for Figma

Welcome to the new Iconify plugin for Figma.

In 2024, the plugin has been completely rewritten. The new version has nothing in common with the old version, so this is a rather radical change, which requires a tutorial.

Failed redesign

This page shows a failed launch of new UI.

For correct page, see plugin update, attempt 2.

What went wrong?

Idea was good, but implementation was horrible. I focused too much on adding features, forgot about user experience.

What was wrong:

This version of plugin was live for 3 days.

After receiving a lot of negative feedback, plugin was reverted to old version. New version was later redesigned from ground up.

... and now back to showing how not to make a release.

New UI

The first change you'll notice immediately is the new layout.

Plugin is designed to fit as much content as possible in the smallest possible space.

Iconify for Figma: main page

You can make it even smaller by clicking the button in navigation to toggle compact width.

Iconify for Figma: compact mode

Due to limited space, the plugin uses tooltips to show additional information.

License information

One of the biggest changes is advanced license information.

Even though all icon sets are open source, not all open source licenses are equal. Some ask for attribution, some prevent commercial use.

The new plugin shows attribution requirement and commercial use limitation in various places:

Iconify for Figma: search results

Additionally, you can filter icon sets and search results by license (see below).

Advanced filters

There are many icon sets, finding an icon set that you want might be a challenge.

The new version of the plugin has advanced filters to help you find icon sets.

You can filter icon sets by:

Iconify for Figma: advanced filters

Favorite icon sets

You can now mark icon sets as favorite.

This can be done by clicking the star button when viewing icon set.

Iconify for Figma: star an icon set

When browsing the icon sets list, if you have marked some icon sets as favorite, you will see the new option to browse only favorite icon sets.

Iconify for Figma: favorite icon sets

All lists (favorite and recent icon sets, recent icons) are considered to be private data (stored in Figma) and can be cleared.

Scrollable icons

Previous versions of the plugin used pagination to show many icons. You needed to click page buttons to show more icons, which was not convenient.

The new version of the plugin has completely redesigned icons view:

Iconify for Figma: icon set

Color styles

When importing icons, you can now pick color styles in color picker.

Due to Figma plugin system limitation, color picker might not show all color styles.

The plugin has access to:

So if you have color styles shared from another document, the plugin might not see them. To add them to color picker, you need to select any layer that uses that color style.

Iconify for Figma: color picker

Solid colors only

Note that the plugin supports only color styles that have one solid color.

Gradients, patterns, colors with opacity are not supported.

Replacing icons

If you have selected a layer that contains icon, which was previously imported with plugin, you will see an option to replace that icon.

Option to replace icon already existed in the previous version of the plugin, but now it has been redesigned.

When replacing an icon, new icon will keep old icon's:

Iconify for Figma: replacing icon

Animated icons

Unfortunately, Figma does not support SVG animations.

But it does not mean you cannot use animated icons in your work.

The new version of the plugin allows you to import animated icons to Figma. It will parse animations, remove animations and import static icon without animations.

This allows you to use animated icon in the design.

In production code, you can copy SVG with full animations from the Iconify website or use Iconify icon components.

Iconify for Figma: animated icons

Removed functions

Not all functions from the old version made it to the new version:

Feedback

Feedback is welcome.

See [str]feedback page in the plugin or visit support page on website.

Design

index

title: Iconify for Penpot
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "70+"
    value: "${counters.sets}+"

Iconify for Penpot

With the Iconify plugin for Penpot you can import over 60,000 vector icons to Penpot.

It is completely free!

Unlike other plugins that offer many icons, but require payment to use SVG, Iconify always imports icons as SVG. Iconify project is open source and offers only open source icon sets.

Plugin remembers the last page you have visited, making it easy to continue searching or browsing icons.

Installation

Plugin is available at Iconify for Penpot GitHub repository.

To install plugin, open plugin manager in Penpot and add the following URL:

https://penpot.iconify.design/manifest.json

Usage

In Penpot menu select [str]Plugins, then select [str]Iconify.

Browse or search icons, select any icon, click [str]Import Icon button or drag icon to the Penpot document.

Themes

Plugin supports both light and dark themes.

To change theme, change theme in Penpot settings.

Screenshots below demonstrate both themes.

Detailed instructions

After opening the plugin, you will see the main page:

Iconify for Penpot: main page

Click any icon set or search icons.

When you click an icon set, the plugin will show you all icons in that icon set. You can filter icons by categories (if the current icon set has them), search icons.

To show more icons, simply scroll the icons list.

Iconify for Penpot: icon set

You can also search all icon sets for icons. For example, search for "home":

Iconify for Penpot: icon search results

The plugin will show you all icons that match your keyword.

When you hover any icon, you will see a button to show more information.

If you hover it, you will see the icon name. If you click it, you will see:

You can import icon by:

Advanced import

When you select an icon, it will appear in page footer with options:

Iconify for Penpot: icon code

For icons that do not have a hardcoded palette, color picker is available, showing recently used colors:

Iconify for Penpot: color picker

Support and feedback

Feedback is welcome.

See [str]feedback page in the plugin or visit support page on website.

Design

index

title: Iconify for Sketch
replacements:
  - code: '60k'
    value: '${counters.icons-short}'
  - code: '60,000'
    value: '${counters.icons}'
  - code: '70+'
    value: '${counters.sets}+'

Iconify for Sketch

Want to add icons to your designs?

Iconify for Sketch got you covered. One plugin offers over 60,000 icons from 70+ icon sets.

With Sketch plug-in you can:

It is completely free! Unlike other plugins that offer many icons, but require payment to use SVG, Iconify always imports icons as SVG. Iconify project is open source and offers only open source icon sets.

Installation

Go to plug-in releases page, download the latest file, unpack it, open [file]iconify.sketchplugin in Finder. Finder should launch Sketch that should install plug-in.

If plug-in installation fails, copy [file]iconify.sketchplugin to [file]~/Library/Application Support/com.bohemiancoding.sketch3/Plugins/.

Usage

In Sketch menu select [str]Plug-ins, then [str]Iconify or press Ctrl+Shift+I.

Browse or search icons, select any icon, click [str]Import button. Plug-in will import icon to your current project.

Screenshots

Importing icon:

Iconify for Sketch: footer

Big choice of [str]home icons:

Iconify for Sketch: search results

Collections list:

Iconify for Sketch: browse collections

Iconify for Sketch: browse collections

Importing multiple icons:

Iconify for Sketch: browsing icons set

Available icons

You can browse and import iver 60k open source icons hosted on Iconify API to Sketch projects.

Source code

All source code is available at Iconify for Sketch repository.

To build it, install all necessary dependencies and run [bash]npm run build. Build script will generate [file]iconify.sketchplugin that you can install.

Icon Components

Icon Components

index

title: Icons on Demand
replacements:
  - code: '60,000'
    value: '${counters.icons}'
  - code: '60k'
    value: '${counters.icons-short}'

Icons on demand

Iconify ecosystem has a unique feature: Iconify API.

It can be used to load icon data on demand and is used by Iconify icon components.

Skip to list of available components if you want to skip long explanation of how it all works.

How does it work? {#process}

Iconify icon components are very easy to use. All developer has to specify is an icon name:

src: icon-components/icon/usage.html
demo: true
demoFirst: false
class: sample-big

Unlike regular icon components, Iconify icon components do not bundle icon data. They load only data for icons used on currently viewed page at run time.

Advantages

Loading icon data on demand has its advantages and disadvantages over using regular icon components.

Advantages:

Disadvantages:

Components

The best option by far is Web component. It is usable in HTML with or without UI frameworks.

Additionally, there are components for UI frameworks: React, Vue, Svelte, Ember.

In future, only [npm]iconify-icon web component will be supported. Why?

Web component {#web-component}

The best option by far is web component. It is the most modern iteration, works with all UI frameworks and works great with server side rendering.

Usage is simple:

<iconify-icon icon="mdi:home"></iconify-icon>

See Iconify icon web component documentation.

Shadow DOM

Web component renders icon in Shadow DOM, separating it from the main document.

That has its advantages and disadvantages over other components.

Advantages:

Disadvantages:

If these disadvantages are unacceptable for your project, use "SVG framework" or one of UI framework specific components listed below.

UI frameworks {#ui-frameworks}

Iconify offers components native to various UI frameworks:

Usage is as any other component:

<Icon icon="mdi:home" />

These components behave differently than the web component:

You should consider using the [npm]iconify-icon web component instead of components mentioned above. Dynamic data loading does not work well with SSR. Web component solves those issues.

Legacy components

In addition to components listed above, there are several legacy components. They were created a long time ago, but no longer relevant in modern development.

These components are no longer updated, but can be used if you really need it:

Icon Components

add-api-provider

title: 'Iconify for Ember Function: addAPIProvider'

Iconify for Ember function: addAPIProvider

This tutorial is part of Iconify for Ember functions tutorial.

include icon-components/functions/add-api-provider/intro

API providers

include icon-components/api-providers

Usage

include icon-components/functions/add-api-provider/props

Example

src: icon-components/ember/add-api-provider.js
title: Adding API provider in JavaScript
extra:
  - src: icon-components/ember/add-api-provider.hbs
    title: Usage in template

include icon-components/functions/add-api-provider/footer

Icon Components

add-collection

title: 'Iconify for Ember Function: addCollection'
types:
  IconifyJSON: '../../types/iconify-json.md'
  IconifyIcon: '../../types/iconify-icon.md'
functions:
  addIcon: './add-icon.md'

Iconify for Ember function: addCollection

This tutorial is part of Iconify for Ember functions tutorial.

include icon-components/functions/add-collection/intro

Usage

include icon-components/functions/add-collection/props

Examples

src: icon-components/common/add-collection.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'
src: icon-components/common/add-collection2.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'

include icon-components/functions/add-collection/notes

API provider

include icon-components/functions/add-collection/provider

Example:

src: icon-components/common/add-collection3.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'

Code above adds only one icon:

In component template this icon can be used like this:

<IconifyIcon @icon='@custom:md:test' />

include icon-components/functions/add-collection/custom

One icon

include icon-components/functions/add-collection/footer

Icon Components

add-icon

title: 'Iconify for Ember Function: addIcon'
types:
  IconifyJSON: '../../types/iconify-json.md'
  IconifyIcon: '../../types/iconify-icon.md'
functions:
  addCollection: './add-collection.md'

Iconify for Ember function: addIcon

This tutorial is part of Iconify for Ember functions tutorial.

include icon-components/functions/add-icon/intro

Usage

include icon-components/functions/add-icon/props

Examples

src: icon-components/common/add-icon.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'

include icon-components/functions/add-icon/notes

API provider

include icon-components/functions/add-icon/provider

Example:

src: icon-components/common/add-icon2.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'

Code above adds the following icon:

In component template this icon can be used like this:

<IconifyIcon @icon='@custom:md:test' />

include icon-components/functions/add-icon/custom

One icon

include icon-components/functions/add-icon/footer

Icon Components

build-icon

title: "Iconify for Ember Function: renderSVG"
types:
  IconifyIcon: "../../types/iconify-icon.md"
functions:
  replaceIDs: "./replace-ids.md"
  getIcon: "./get-icon.md"
  loadIcon: "./load-icon.md"
  iconExists: "./icon-exists.md"
  iconLoaded: "./icon-exists.md"

Iconify for Ember function: buildIcon

This tutorial is part of Iconify for Ember functions tutorial.

include icon-components/functions/build-icon/intro-component

Usage

include icon-components/functions/build-icon/usage

Result

include icon-components/functions/build-icon/result

Customizations

Second parameter is optional icon customizations. Available customizations:

include icon-components/customisations

For more details about dimensions see icon dimensions documentation.

For more details about transformations see icon transformations documentation.

Example

src: icon-components/common/build-icon.js
replacements:
  - search: "@iconify/svelte"
    replace: "@iconify/ember/components/iconify-icon"
extra:
  - src: icon-components/common/build-icon.json
    title: "Result:"
Icon Components

color

title: Changing Icon Color in Iconify for Ember

Icon color

This tutorial is part of Iconify for Ember tutorial.

include: icon-components/components/color-intro
src: icon-components/ember/color.hbs
css: components/color.scss
demo: icon-components/common/color.html
class: components-color
include: icon-components/components/color-intro2

RGBA and HSLA colors {#opacity}

include icon-components/color-rgba

fill and stroke

include icon-components/color-fill

Icon Components

dimensions

title: Changing Icon Dimensions in Iconify for Ember

Icon dimensions

This tutorial is part of Iconify for Ember tutorial.

include: icon-components/components/size-intro
src: icon-components/ember/size.hbs
css: components/size.scss
demo: icon-components/common/size.html
class: components-size

If you want to control icon size with [prop]width and [prop]height in CSS, see how to remove icon dimensions section below.

Units

include: icon-components/components/size-units
<IconifyIcon @icon='mdi:home' @height={{24}} />
<IconifyIcon @icon='mdi:home' @height='24' />
<IconifyIcon @icon='mdi:home' @height='24px' />
<IconifyIcon @icon='mdi:home' @height='1.5em' style='font-size: 16px;' />

Keyword "auto" {#auto}

include: icon-components/components/size-auto
<IconifyIcon @icon="mdi: home;" height="auto" />

Keywords "none" and "unset" {#unset}

include: icon-components/components/size-unset
src: icon-components/ember/size-unset.hbs
demo: icon-components/common/size-unset.html
class: 'icon-size icon-size--unset'
include: icon-components/components/size-unset-footer

Setting only width or height

In an example above, all icons only use [prop]height.

include icon-components/size-one

Example

include icon-components/size-example

Alignment

include icon-components/align-header

src: icon-components/ember/alignment.hbs
demo: icon-components/common/alignment.html
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

include icon-components/align-behavior

Icon Components

disable-cache

title: 'Iconify for Ember Function: disableCache'
functions:
  enableCache: './enable-cache.md'
  addIcon: './add-icon.md'
  addCollection: './add-collection.md'

Iconify for Ember function: disableCache

This tutorial is part of Iconify for Ember functions tutorial.

include icon-components/functions/cache/intro-disable

Usage

include icon-components/functions/cache/props

Storage types

include icon-components/functions/cache/storage-types

Examples

src: icon-components/common/disable-cache.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'

Another example:

src: icon-components/common/disable-cache2.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'

Notes

include icon-components/functions/cache/notes

Icon Components

enable-cache

title: 'Iconify for Ember Function: enableCache'
functions:
  disableCache: './disable-cache.md'
  addIcon: './add-icon.md'
  addCollection: './add-collection.md'

Iconify for Ember function: enableCache

This tutorial is part of Iconify for Ember functions tutorial.

include icon-components/functions/cache/intro-enable

Usage

include icon-components/functions/cache/props

Storage types

include icon-components/functions/cache/storage-types

Example

src: icon-components/common/enable-cache.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'

Notes

include icon-components/functions/cache/notes

Icon Components

get-icon

title: 'Iconify for Ember Function: getIcon'
types:
  IconifyIcon: '/docs/types/iconify-icon.md'

Iconify for Ember function: getIcon

This tutorial is part of Iconify for Ember functions tutorial.

include icon-components/functions/get-icon/intro

Usage

include icon-components/functions/get-icon/props

Examples

src: icon-components/common/get-icon.js
extra:
  - src: icon-components/iconify/get-icon.json
    title: 'Result:'
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'

Another example:

src: icon-components/common/get-icon2.js
extra:
  - src: icon-components/iconify/get-icon2.json
    title: 'Result:'
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'

Example with bad icon name, returns null:

src: icon-components/common/get-icon-null.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'
Icon Components

icon-exists

title: 'Iconify for Ember Function: iconExists'
functions:
  getIcon: './get-icon.md'
  loadIcons: './load-icons.md'

Iconify for Ember function: iconExists

This tutorial is part of Iconify for Ember functions tutorial.

include icon-components/functions/icon-exists/intro

Usage

include icon-components/functions/icon-exists/props

Example

import { iconExists } from '@iconify/ember/components/iconify-icon';

const icon = 'bi:arrow-left';
console.log(`Is ${icon} available?`, iconExists(icon) ? 'yes' : 'no');
Icon Components

icon-name

title: 'Iconify Type: IconifyIconName'

IconifyIconName type

include types/iconify-icon-name

API providers

include icon-components/api-providers-short

Examples

src: icon-components/iconify/icon-name.json
title: 'md:home'
hint: Because prefix does not contain hyphen, icon can also be referred as 'md-home'

Another example:

src: icon-components/iconify/icon-name2.json
title: '@local:line-icons:arrow-left'
Icon Components

index

title: Iconify for Ember
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "80+"
    value: "${counters.sets}+"
types:
  IconifyIcon: "../../types/iconify-icon.md"
functions:
  addCollection: "./add-collection.md"
  addIcon: "./add-icon.md"
  iconExists: "./icon-exists.md"
  iconLoaded: "./icon-exists.md"
  listIcons: "./list-icons.md"
  loadIcons: "./load-icons.md"
  loadIcon: "./load-icon.md"
  getIcon: "./get-icon.md"
  enableCache: "./enable-cache.md"
  disableCache: "./disable-cache.md"
  addAPIProvider: "./add-api-provider.md"
  replaceIDs: "./replace-ids.md"
  buildIcon: "./build-icon.md"
  setFetch: "./set-fetch.md"

Iconify for Ember

include: icon-components/components/intro
replacements:
  - search: React
    replace: Ember

Please be aware that this component is no longer maintained. Ember is an outdated framework. If you are using Ember, consider switching to Iconify Icon web component.

Installation

If you are using NPM:

npm install --save-dev @iconify/ember

If you are using Yarn:

yarn add --dev @iconify/ember

Usage

No need to import anything, Iconify for Ember is designed as addon for Ember, so Ember will automatically import component.

In template use [var]IconifyIcon component with imported icon name as [prop]icon parameter:

<IconifyIcon @icon="mdi-light:home" />

Properties

In Ember, all component properties start with [prop]@, such as [prop]@icon.

Required properties:

include: icon-components/component-optional-props
replacements:
  - search: '<span class="hljs-inline-prop">'
    replace: '<span class="hljs-inline-prop">@'

See below for more information on each optional property.

Icon

include: icon-components/components/intro-icon

Color

include: icon-components/components/intro-color
<IconifyIcon @icon="mdi:home" style="color: red;" />

For various ways to set color, see how to change icon color in Iconify for Ember.

Dimensions

include: icon-components/components/intro-size
<IconifyIcon @icon="mdi:home" style="font-size: 24px;" />

For various ways to change icon dimensions, see how to change icon dimensions in Iconify for Ember.

Transformations

include: icon-components/components/intro-transform

For more details see how to transform icon in Iconify for Ember.

onLoad

include icon-components/components/onload

SVG element properties

Any property that does not start with [prop]@ is passed to SVG element. You can use that to set style, class name, id or even override properties generated by component.

<IconifyIcon @icon="mdi:home" id="test" />

This behavior is different from other components. Ember clearly separates component and element properties, other frameworks do not.

Functions {#functions}

Component exports various functions, which developers can use to control icons.

In other frameworks you can import functions from main file, but Ember behaves differently. In Ember component, functions need to be imported directly from component file: [file]@iconify/ember/components/iconify-icon.

Functions are split in several groups (click function name to see more details and examples):

Check available icons {#getting-icons}

include: icon-components/components/functions-list/getting-icons

Adding icons {#adding-icons}

include: icon-components/components/functions-list/adding-icons

Helper functions {#helper}

include: icon-components/components/functions-list/helpers

API functions {#api}

include: icon-components/components/functions-list/api

Internal API functions {#internal}

include: icon-components/components/functions-list/internal
Icon Components

inline

title: Vertical Alignment in Iconify for Ember

Vertical alignment

This tutorial is part of Iconify for Ember tutorial.

include icon-components/vertical-align-intro

Inline attribute

Instead of adding [prop]vertical-align to each icon, icon component has a property [prop]inline. Adding [prop]inline property to icon component is identical to setting [html]style="vertical-align: -0.125em":

src: icon-components/ember/inline.hbs
demo: icon-components/common/inline.html
class: iconify-inline-block

include icon-components/vertical-align-footer

Icon Components

list-icons

title: 'Iconify for Ember Function: listIcons'

Iconify for Ember function: listIcons

This tutorial is part of Iconify for Ember functions tutorial.

include icon-components/functions/list-icons/intro

Usage

include icon-components/functions/list-icons/props

Examples

src: icon-components/common/list-icons.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'

Another example:

src: icon-components/common/list-icons2.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'
Icon Components

load-icon

title: 'Iconify for Ember Function: loadIcon'
types:
  IconifyIconName: './icon-name.md'
  FullIconifyIcon: '/docs/libraries/utils/full-iconify-icon.md'
functions:
  loadIcons: './load-icons.md'

Iconify for Ember function: loadIcon

This tutorial is part of Iconify for Ember functions tutorial.

include icon-components/functions/load-icon/intro

Usage

include icon-components/functions/load-icon/props

IconifyIconName type

include types/iconify-icon-name

Examples

Using [type]Promise syntax:

src: icon-components/common/load-icon.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'

Async/await syntax:

src: icon-components/common/load-icon-async.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'

If you want to load multiple icons, see [func]loadIcons().

Icon Components

load-icons

title: 'Iconify for Ember Function: loadIcons'
types:
  IconifyIconName: './icon-name.md'
functions:
  getIcon: './get-icon.md'
  loadIcon: './load-icon.md'

Iconify for Ember function: loadIcons

This tutorial is part of Iconify for Ember functions tutorial.

include icon-components/functions/load-icons/intro

Usage

include icon-components/functions/load-icons/props

Icons list

include icon-components/functions/load-icons/props-icons

Callback

include icon-components/functions/load-icons/props-callback

IconifyIconName type

include types/iconify-icon-name

Examples

Simple callback that loads one icon:

src: icon-components/common/load-icons.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'

Async version of [func]loadIcons():

src: icon-components/common/load-icons-async.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'

If you want to load only one icon, there is also [func]loadIcon() that is easier to use.

Icon Components

replace-ids

title: 'Iconify for Ember Function: replaceIDs'
functions:
  getIcon: './get-icon.md'

Iconify for Ember function: replaceIDs

This tutorial is part of Iconify for Ember functions tutorial.

include icon-components/functions/replace-ids/intro-component

Usage

include icon-components/functions/replace-ids/props

Example

include icon-components/functions/replace-ids/example-component

src: icon-components/common/replace-ids.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/ember/components/iconify-icon'
Icon Components

set-fetch

title: 'Iconify for Ember Function: setFetch'

Iconify for Ember function: setFetch

This tutorial is part of Iconify for Ember functions tutorial.

include icon-components/functions/set-fetch/intro-component

Why is it needed? {#why}

include: icon-components/functions/set-fetch/why
include: icon-components/functions/set-fetch/nodejs

Usage

include: icon-components/functions/set-fetch/usage

Steps

include: icon-components/functions/set-fetch/component
replacements:
  - search: '@iconify/svelte'
    replace: '@iconify/ember/components/iconify-icon'
include: icon-components/functions/set-fetch/bundle
Icon Components

transform

title: Transforming Icon in Iconify for Ember

Transformations

This tutorial is part of Iconify for Ember tutorial.

include icon-components/transform-intro

CSS vs Iconify transformations {#css}

include icon-components/transform-compare

Example:

src: icon-components/ember/rotate-comparison.hbs
demo: icon-components/common/rotate-comparison.html
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

include icon-components/transform-compare-footer

Flip

include: icon-components/components/transform-flip
src: icon-components/ember/flip.hbs
hint: Using "flip" attribute
demo: icon-components/common/flip.html
extra:
  - src: icon-components/ember/flip-alt.hbs
    hint: Using "hFlip" and "vFlip" attributes

Rotation

include icon-components/components/transform-rotate

src: icon-components/ember/rotate.hbs
demo: icon-components/common/rotate.html

Rotate and flip

include icon-components/components/transform-footer

Icon Components

add-api-provider

title: 'Iconify for React Function: addAPIProvider'

Iconify for React function: addAPIProvider

This tutorial is part of Iconify for React functions tutorial.

include icon-components/functions/add-api-provider/intro

API providers

include icon-components/api-providers

Usage

include icon-components/functions/add-api-provider/props

Example

src: icon-components/common/add-api-provider.jsx

include icon-components/functions/add-api-provider/footer

Icon Components

add-collection

title: 'Iconify for React Function: addCollection'
types:
  IconifyJSON: '../../types/iconify-json.md'
  IconifyIcon: '../../types/iconify-icon.md'
functions:
  addIcon: './add-icon.md'

Iconify for React function: addCollection

This tutorial is part of Iconify for React functions tutorial.

include icon-components/functions/add-collection/intro

Usage

include icon-components/functions/add-collection/props

Examples

src: icon-components/common/add-collection.js
src: icon-components/common/add-collection2.js

include icon-components/functions/add-collection/notes

API provider

include icon-components/functions/add-collection/provider

Example:

src: icon-components/common/add-collection3.js

Code above adds only one icon:

In component JSX this icon can be used like this:

<Icon icon="@custom:md:test" />

include icon-components/functions/add-collection/custom

One icon

include icon-components/functions/add-collection/footer

Icon Components

add-icon

title: 'Iconify for React Function: addIcon'
types:
  IconifyJSON: '../../types/iconify-json.md'
  IconifyIcon: '../../types/iconify-icon.md'
functions:
  addCollection: './add-collection.md'

Iconify for React function: addIcon

This tutorial is part of Iconify for React functions tutorial.

include icon-components/functions/add-icon/intro

Usage

include icon-components/functions/add-icon/props

Examples

src: icon-components/common/add-icon.js

include icon-components/functions/add-icon/notes

API provider

include icon-components/functions/add-icon/provider

Example:

src: icon-components/common/add-icon2.js

Code above adds the following icon:

In component JSX this icon can be used like this:

<Icon icon="@custom:md:test" />

include icon-components/functions/add-icon/custom

One icon

include icon-components/functions/add-icon/footer

Icon Components

build-icon

title: "Iconify for React Function: renderSVG"
types:
  IconifyIcon: "../../types/iconify-icon.md"
functions:
  replaceIDs: "./replace-ids.md"
  getIcon: "./get-icon.md"
  loadIcon: "./load-icon.md"
  iconLoaded: "./icon-exists.md"

Iconify for React function: buildIcon

This tutorial is part of Iconify for React functions tutorial.

include icon-components/functions/build-icon/intro-component

Usage

include icon-components/functions/build-icon/usage

Result

include icon-components/functions/build-icon/result

Customizations

Second parameter is optional icon customizations. Available customizations:

include icon-components/customisations

For more details about dimensions see icon dimensions documentation.

For more details about transformations see icon transformations documentation.

Example

src: icon-components/common/build-icon.js
replacements:
  - search: "@iconify/svelte"
    replace: "@iconify/react"
extra:
  - src: icon-components/common/build-icon.json
    title: "Result:"
Icon Components

color

title: Changing Icon Color in Iconify for React

Icon color

This tutorial is part of Iconify for React tutorial.

include: icon-components/components/color-intro
src: icon-components/common/color.jsx
css: components/color.scss
demo: true
class: components-color
include: icon-components/components/color-intro2

RGBA and HSLA colors {#opacity}

include icon-components/color-rgba

fill and stroke

include icon-components/color-fill

Icon Components

custom-loaders

title: "Iconify for React Functions: setCustomIconLoader and setCustomIconsLoader"
types:
  IconifyJSON: "../../types/iconify-json.md"
  IconifyIcon: "../../types/iconify-icon.md"
functions:
  loadIcon: "./load-icon.md"

Custom icon loaders

This tutorial is part of Iconify for React tutorial.

include icon-components/functions/set-loaders/intro

Usage

include icon-components/functions/set-loaders/props

Example

src: icon-components/common/set-loader.js

Make sure loader is set before any icons are rendered, otherwise component might attempt to load icon from API and fail to render it.

Icon Components

dimensions

title: Changing Icon Dimensions in Iconify for React

Icon dimensions

This tutorial is part of Iconify for React tutorial.

include: icon-components/components/size-intro
src: icon-components/common/size.jsx
css: components/size.scss
demo: true
class: components-size

If you want to control icon size with [prop]width and [prop]height in CSS, see how to remove icon dimensions section below.

Units

include: icon-components/components/size-units
<JSXWrapper>
// Number
<Icon icon="mdi:home" height={24} />
// String without units
<Icon icon="mdi:home" height="24" />
// String with units
<Icon icon="mdi:home" height="24px" />
// String with units, font-size is 16px
<Icon icon="mdi:home" height="1.5em" />
</JSXWrapper>

Keyword "auto" {#auto}

include: icon-components/components/size-auto
<Icon icon="mdi:home" height="auto" />

Keywords "none" and "unset" {#unset}

include: icon-components/components/size-unset
src: icon-components/common/size-unset.jsx
demo: true
class: 'icon-size icon-size--unset'
include: icon-components/components/size-unset-footer

Setting only width or height

In an example above, all icons only use [prop]height.

include icon-components/size-one

Example

include icon-components/size-example

Alignment

include icon-components/align-header

src: icon-components/common/alignment.jsx
demo: true
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

include icon-components/align-behavior

Icon Components

disable-cache

title: "Iconify for React Function: disableCache"
functions:
  enableCache: "./enable-cache.md"
  addIcon: "./add-icon.md"
  addCollection: "./add-collection.md"

Iconify for React function: disableCache

This tutorial is part of Iconify for React functions tutorial.

include icon-components/functions/cache/deprecated

include icon-components/functions/cache/intro-disable

Usage

include icon-components/functions/cache/props

Storage types

include icon-components/functions/cache/storage-types

Examples

src: icon-components/common/disable-cache.js

Another example:

src: icon-components/common/disable-cache2.js

Notes

include icon-components/functions/cache/notes

Icon Components

enable-cache

title: "Iconify for React Function: enableCache"
functions:
  disableCache: "./disable-cache.md"
  addIcon: "./add-icon.md"
  addCollection: "./add-collection.md"

Iconify for React function: enableCache

This tutorial is part of Iconify for React functions tutorial.

include icon-components/functions/cache/deprecated

include icon-components/functions/cache/intro-enable

Usage

include icon-components/functions/cache/props

Storage types

include icon-components/functions/cache/storage-types

Example

src: icon-components/common/enable-cache.js

Notes

include icon-components/functions/cache/notes

Icon Components

get-icon

title: 'Iconify for React Function: getIcon'
types:
  IconifyIcon: '/docs/types/iconify-icon.md'

Iconify for React function: getIcon

This tutorial is part of Iconify for React functions tutorial.

include icon-components/functions/get-icon/intro

Usage

include icon-components/functions/get-icon/props

Examples

src: icon-components/common/get-icon.js
extra:
  - src: icon-components/iconify/get-icon.json
    title: 'Result:'

Another example:

src: icon-components/common/get-icon2.js
extra:
  - src: icon-components/iconify/get-icon2.json
    title: 'Result:'

Example with bad icon name, returns null:

src: icon-components/common/get-icon-null.js
Icon Components

icon-exists

title: "Iconify for React Function: iconLoaded"

Iconify for React function: iconLoaded

This tutorial is part of Iconify for React functions tutorial.

include icon-components/functions/icon-loaded/intro

Usage

include icon-components/functions/icon-loaded/props

Example

import { iconLoaded, loadIcons, Icon } from "@iconify/react";

function renderLeftArrow() {
  // Check if 'bi:arrow-left' is available
  if (iconLoaded("bi:arrow-left")) {
    // Return HTML for 'bi:arrow-left'
    return <Icon icon="bi:arrow-left" />;
  }

  // Load icon. Bad example because this should use a callback to re-render arrow in a stateful
  // component, but this code example is about iconLoaded(), not loadIcons()

  // Function loadIcons() is asynchronous, so in this example it will only trigger loading, but
  // icon data will not be available immediately
  loadIcons(["bi:arrow-left"]);

  // Return '<'
  return <span>&lt;</span>;
}

Legacy

include icon-components/functions/icon-loaded/legacy

Icon Components

icon-name

title: 'Iconify Type: IconifyIconName'

IconifyIconName type

include types/iconify-icon-name

API providers

include icon-components/api-providers-short

Examples

src: icon-components/iconify/icon-name.json
title: 'md:home'
hint: Because prefix does not contain hyphen, icon can also be referred as 'md-home'

Another example:

src: icon-components/iconify/icon-name2.json
title: '@local:line-icons:arrow-left'
Icon Components

index

title: Iconify for React
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "80+"
    value: "${counters.sets}+"
  - code: "@iconify/react@2"
    value: "${react.import}"
types:
  IconifyIcon: "../../types/iconify-icon.md"
functions:
  addCollection: "./add-collection.md"
  addIcon: "./add-icon.md"
  iconLoaded: "./icon-exists.md"
  listIcons: "./list-icons.md"
  loadIcons: "./load-icons.md"
  loadIcon: "./load-icon.md"
  getIcon: "./get-icon.md"
  enableCache: "./enable-cache.md"
  disableCache: "./disable-cache.md"
  addAPIProvider: "./add-api-provider.md"
  replaceIDs: "./replace-ids.md"
  buildIcon: "./build-icon.md"
  setCustomIconLoader: "./custom-loaders.md"
  setCustomIconsLoader: "./custom-loaders.md"

Iconify for React

include: icon-components/components/intro

Installation

If you are using NPM:

npm install --save-dev @iconify/react@2

If you are using Yarn:

yarn add --dev @iconify/react@2

Version 4

As of version 5, the component is a modern functional component that uses React hooks.

If you want to use the icon component with an older version of React, you can install version 4 using [npm]@legacy tag:

npm install --save-dev @iconify/react@legacy

Usage

Install [npm]@iconify/react@2 and import [var]Icon component from it:

import { Icon } from "@iconify/react";

Then use [var]Icon component with icon name as [prop]icon parameter:

<Icon icon="mdi-light:home" />
include: icon-components/components/intro-online

Next.js {#ssr}

Component is compatible with the latest Next.js.

Unfortunately, Next.js currently does not support [func]useState in components, making it impossible to use the same stateful components on server and client, so the icon component is a client-only component. SVG will not be rendered on server.

Additionally, to avoid hydration errors, component renders SVG only after it is mounted, which can sometimes cause a tiny delay. If you are using Next.js or similar framework, consider switching to Iconify Icon web component.

If you do want to render SVGs without a delay, provide icon data as parameter instead of icon name or use a different way to render icons, such as:

Properties

You can pass any custom properties to [var]Icon.

Required properties:

include icon-components/component-optional-props

See below for more information on each optional property.

In addition to the properties mentioned above, the icon component accepts any other properties and events. All other properties and events will be passed to generated SVG element, so you can do stuff like assigning [prop]onClick event, setting the inline style, add title and so on.

Icon

include: icon-components/components/intro-icon

Color

include: icon-components/components/intro-color
<Icon icon="mdi:home" style={{ color: "red" }} />

For various ways to set color, see how to change icon color in Iconify for React.

Dimensions

include: icon-components/components/intro-size
<Icon icon="mdi:home" style={{ fontSize: "24px" }} />

For various ways to change icon dimensions, see how to change icon dimensions in Iconify for React.

Transformations

include: icon-components/components/intro-transform

For more details see how to transform icon in Iconify for React.

onLoad

include icon-components/components/onload

Functions {#functions}

include: icon-components/components/functions-list/header

Check available icons {#getting-icons}

include: icon-components/components/functions-list/getting-icons

Adding icons {#adding-icons}

include: icon-components/components/functions-list/adding-icons

Custom loaders {#custom-loaders}

include: icon-components/components/functions-list/custom-loaders

Helper functions {#helper}

include: icon-components/components/functions-list/helpers

API functions {#api}

include: icon-components/components/functions-list/api

Internal API functions {#internal}

include: icon-components/components/functions-list/internal
Icon Components

inline

title: Vertical Alignment in Iconify for React

Vertical alignment

This tutorial is part of Iconify for React tutorial.

include icon-components/vertical-align-intro

Inline attribute

include icon-components/components/inline-react

src: icon-components/common/inline.jsx
demo: true
class: iconify-inline-block

include icon-components/vertical-align-footer

Icon Components

list-icons

title: 'Iconify for React Function: listIcons'

Iconify for React function: listIcons

This tutorial is part of Iconify for React functions tutorial.

include icon-components/functions/list-icons/intro

Usage

include icon-components/functions/list-icons/props

Examples

src: icon-components/common/list-icons.js

Another example:

src: icon-components/common/list-icons2.js
Icon Components

load-icon

title: 'Iconify for React Function: loadIcon'
types:
  IconifyIconName: './icon-name.md'
  FullIconifyIcon: '/docs/libraries/utils/full-iconify-icon.md'
functions:
  loadIcons: './load-icons.md'

Iconify for React function: loadIcon

This tutorial is part of Iconify for React functions tutorial.

include icon-components/functions/load-icon/intro

Usage

include icon-components/functions/load-icon/props

IconifyIconName type

include types/iconify-icon-name

Examples

Using [type]Promise syntax:

src: icon-components/common/load-icon.js

Async/await syntax:

src: icon-components/common/load-icon-async.js

If you want to load multiple icons, see [func]loadIcons().

Icon Components

load-icons

title: 'Iconify for React Function: loadIcons'
functions:
  getIcon: './get-icon.md'
  loadIcon: './load-icon.md'
types:
  IconifyIconName: './icon-name.md'

Iconify for React function: loadIcons

This tutorial is part of Iconify for React functions tutorial.

include icon-components/functions/load-icons/intro

Usage

include icon-components/functions/load-icons/props

Icons list

include icon-components/functions/load-icons/props-icons

Callback

include icon-components/functions/load-icons/props-callback

IconifyIconName type

include types/iconify-icon-name

Examples

Simple callback that loads one icon:

src: icon-components/common/load-icons.js

Async version of [func]loadIcons():

src: icon-components/common/load-icons-async.js

If you want to load only one icon, there is also [func]loadIcon() that is easier to use.

Icon Components

replace-ids

title: 'Iconify for React Function: replaceIDs'
functions:
  getIcon: './get-icon.md'

Iconify for React function: replaceIDs

This tutorial is part of Iconify for React functions tutorial.

include icon-components/functions/replace-ids/intro-component

Usage

include icon-components/functions/replace-ids/props

Example

include icon-components/functions/replace-ids/example-component

src: icon-components/common/replace-ids.js
Icon Components

set-fetch

title: 'Iconify for React Function: setFetch'

Iconify for React function: setFetch

This tutorial is part of Iconify for React functions tutorial.

include icon-components/functions/set-fetch/intro-component

Why is it needed? {#why}

include: icon-components/functions/set-fetch/why
include: icon-components/functions/set-fetch/nodejs

Usage

include: icon-components/functions/set-fetch/usage

Steps

include: icon-components/functions/set-fetch/component
replacements:
  - search: '@iconify/svelte'
    replace: '@iconify/react'
include: icon-components/functions/set-fetch/bundle
Icon Components

transform

title: Transforming Icon in Iconify for React

Transformations

This tutorial is part of Iconify for React tutorial.

include icon-components/transform-intro

CSS vs Iconify transformations {#css}

include icon-components/transform-compare

Example:

src: icon-components/common/rotate-comparison.jsx
demo: true
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

include icon-components/transform-compare-footer

Flip

include icon-components/components/transform-flip

src: icon-components/common/flip.jsx
hint: Using "flip" attribute
demo: true
extra:
  - src: icon-components/common/flip-alt.jsx
    hint: Using "hFlip" and "vFlip" attributes

Rotation

include icon-components/components/transform-rotate

src: icon-components/common/rotate.jsx
demo: true

Rotate and flip

include icon-components/components/transform-footer

Icon Components

add-api-provider

title: 'Iconify for Svelte Function: addAPIProvider'

Iconify for Svelte function: addAPIProvider

This tutorial is part of Iconify for Svelte functions tutorial.

include icon-components/functions/add-api-provider/intro

API providers

include icon-components/api-providers

Usage

include icon-components/functions/add-api-provider/props

Example

src: icon-components/common/add-api-provider.svelte

include icon-components/functions/add-api-provider/footer

Icon Components

add-collection

title: 'Iconify for Svelte Function: addCollection'
types:
  IconifyJSON: '../../types/iconify-json.md'
  IconifyIcon: '../../types/iconify-icon.md'
functions:
  addIcon: './add-icon.md'

Iconify for Svelte function: addCollection

This tutorial is part of Iconify for Svelte functions tutorial.

include icon-components/functions/add-collection/intro

Usage

include icon-components/functions/add-collection/props

Examples

src: icon-components/common/add-collection.js
replacements:
  - search: react
    replace: svelte
src: icon-components/common/add-collection2.js
replacements:
  - search: react
    replace: svelte

include icon-components/functions/add-collection/notes

API provider

include icon-components/functions/add-collection/provider

Example:

src: icon-components/common/add-collection3.js
replacements:
  - search: react
    replace: svelte

Code above adds only one icon:

In component template code this icon can be used like this:

<Icon icon="@custom:md:test" />

include icon-components/functions/add-collection/custom

One icon

include icon-components/functions/add-collection/footer

Icon Components

add-icon

title: 'Iconify for Svelte Function: addIcon'
types:
  IconifyJSON: '../../types/iconify-json.md'
  IconifyIcon: '../../types/iconify-icon.md'
functions:
  addCollection: './add-collection.md'

Iconify for Svelte function: addIcon

This tutorial is part of Iconify for Svelte functions tutorial.

include icon-components/functions/add-icon/intro

Usage

include icon-components/functions/add-icon/props

Examples

src: icon-components/common/add-icon.js
replacements:
  - search: react
    replace: svelte

include icon-components/functions/add-icon/notes

API provider

include icon-components/functions/add-icon/provider

Example:

src: icon-components/common/add-icon2.js
replacements:
  - search: react
    replace: svelte

Code above adds the following icon:

In component template this icon can be used like this:

<Icon icon="@custom:md:test" />

include icon-components/functions/add-icon/custom

One icon

include icon-components/functions/add-icon/footer

Icon Components

build-icon

title: 'Iconify for Svelte Function: renderSVG'
types:
  IconifyIcon: '../../types/iconify-icon.md'
functions:
  replaceIDs: './replace-ids.md'
  getIcon: './get-icon.md'
  loadIcon: './load-icon.md'
  iconExists: './icon-exists.md'

Iconify for Svelte function: buildIcon

This tutorial is part of Iconify for Svelte functions tutorial.

include icon-components/functions/build-icon/intro-component

Usage

include icon-components/functions/build-icon/usage

Result

include icon-components/functions/build-icon/result

Customizations

Second parameter is optional icon customizations. Available customizations:

include icon-components/customisations

For more details about dimensions see icon dimensions documentation.

For more details about transformations see icon transformations documentation.

Example

src: icon-components/common/build-icon.js
extra:
  - src: icon-components/common/build-icon.json
    title: 'Result:'
Icon Components

color

title: Changing Icon Color in Iconify for Svelte

Icon color

This tutorial is part of Iconify for Svelte tutorial.

include: icon-components/components/color-intro
src: icon-components/common/color.svelte
demo: true
class: components-color
include: icon-components/components/color-intro2

RGBA and HSLA colors {#opacity}

include icon-components/color-rgba

fill and stroke

include icon-components/color-fill

Icon Components

custom-loaders

title: "Iconify for Svelte Functions: setCustomIconLoader and setCustomIconsLoader"
types:
  IconifyJSON: "../../types/iconify-json.md"
  IconifyIcon: "../../types/iconify-icon.md"
functions:
  loadIcon: "./load-icon.md"

Custom icon loaders

This tutorial is part of Iconify for Svelte tutorial.

include icon-components/functions/set-loaders/intro

Usage

include icon-components/functions/set-loaders/props

Example

src: icon-components/common/set-loader.js
replacements:
  - search: "@iconify/react"
    replace: "@iconify/svelte"

Make sure loader is set before any icons are rendered, otherwise component might attempt to load icon from API and fail to render it.

Icon Components

dimensions

title: Changing Icon Dimensions in Iconify for Svelte

Icon dimensions

This tutorial is part of Iconify for Svelte tutorial.

include: icon-components/components/size-intro
src: icon-components/common/size.svelte
demo: true
class: components-size

If you want to control icon size with [prop]width and [prop]height in CSS, see how to remove icon dimensions section below.

Units

include: icon-components/components/size-units
<JSXWrapper>
// Number
<Icon icon="mdi:home" height={24} />
// String without units
<Icon icon="mdi:home" height="24" />
// String with units
<Icon icon="mdi:home" height="24px" />
// String with units, font-size is 16px
<Icon icon="mdi:home" height="1.5em" />
</JSXWrapper>

Keyword "auto" {#auto}

include: icon-components/components/size-auto
<Icon icon="mdi:home" height="auto" />

Keywords "none" and "unset" {#unset}

include: icon-components/components/size-unset
src: icon-components/common/size-unset.svelte
demo: true
class: 'icon-size icon-size--unset'
include: icon-components/components/size-unset-footer

Setting only width or height

In an example above, all icons only use [prop]height.

include icon-components/size-one

Example

include icon-components/size-example

Alignment

include icon-components/align-header

src: icon-components/common/alignment.jsx
demo: true
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

include icon-components/align-behavior

Icon Components

disable-cache

title: "Iconify for Svelte Function: disableCache"
functions:
  enableCache: "./enable-cache.md"
  addIcon: "./add-icon.md"
  addCollection: "./add-collection.md"

Iconify for Svelte function: disableCache

This tutorial is part of Iconify for Svelte functions tutorial.

include icon-components/functions/cache/deprecated

include icon-components/functions/cache/intro-disable

Usage

include icon-components/functions/cache/props

Storage types

include icon-components/functions/cache/storage-types

Examples

src: icon-components/common/disable-cache.js
replacements:
  - search: react
    replace: svelte

Another example:

src: icon-components/common/disable-cache2.js
replacements:
  - search: react
    replace: svelte

Notes

include icon-components/functions/cache/notes

Icon Components

enable-cache

title: "Iconify for Svelte Function: enableCache"
functions:
  disableCache: "./disable-cache.md"
  addIcon: "./add-icon.md"
  addCollection: "./add-collection.md"

Iconify for Svelte function: enableCache

This tutorial is part of Iconify for Svelte functions tutorial.

include icon-components/functions/cache/deprecated

include icon-components/functions/cache/intro-enable

Usage

include icon-components/functions/cache/props

Storage types

include icon-components/functions/cache/storage-types

Example

src: icon-components/common/enable-cache.js
replacements:
  - search: react
    replace: svelte

Notes

include icon-components/functions/cache/notes

Icon Components

get-icon

title: 'Iconify for Svelte Function: getIcon'
types:
  IconifyIcon: '/docs/types/iconify-icon.md'

Iconify for Svelte function: getIcon

This tutorial is part of Iconify for Svelte functions tutorial.

include icon-components/functions/get-icon/intro

Usage

include icon-components/functions/get-icon/props

Examples

src: icon-components/common/get-icon.js
extra:
  - src: icon-components/iconify/get-icon.json
    title: 'Result:'
replacements:
  - search: react
    replace: svelte

Another example:

src: icon-components/common/get-icon2.js
extra:
  - src: icon-components/iconify/get-icon2.json
    title: 'Result:'
replacements:
  - search: react
    replace: svelte

Example with bad icon name, returns null:

src: icon-components/common/get-icon-null.js
replacements:
  - search: react
    replace: svelte

Svelte component example

This example renders [html]<slot /> while icon is being loaded, emulating behavior of React component. Due to bug in Svelte, third party components cannot use [html]<slot />, so Svelte component behaves a bit different than other components.

src: icon-components/common/get-icon.svelte
Icon Components

icon-exists

title: "Iconify for Svelte Function: iconLoaded"
functions:
  getIcon: "./get-icon.md"

Iconify for Svelte function: iconLoaded

This tutorial is part of Iconify for Svelte functions tutorial.

include icon-components/functions/icon-loaded/intro

Usage

include icon-components/functions/icon-loaded/props

Example

This example renders [prop]fallback snippet while icon is being loaded.

src: icon-components/common/icon-exists.svelte

Usage example:

<IconWrapper icon="mdi-light:alert">
    {#snippet fallback()}
        <small>!</small>
    {/snippet}
</IconWrapper>

This example uses [func]iconLoaded() to show function, but for this purpose it is better to use [func]getIcon(). See [func]getIcon() documentation for better example.

Legacy

include icon-components/functions/icon-loaded/legacy

Icon Components

icon-name

title: 'Iconify Type: IconifyIconName'

IconifyIconName type

include types/iconify-icon-name

API providers

include icon-components/api-providers-short

Examples

src: icon-components/iconify/icon-name.json
title: 'md:home'
hint: Because prefix does not contain hyphen, icon can also be referred as 'md-home'

Another example:

src: icon-components/iconify/icon-name2.json
title: '@local:line-icons:arrow-left'
Icon Components

index

title: Iconify for Svelte
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "80+"
    value: "${counters.sets}+"
  - code: "@iconify/svelte@2"
    value: "${svelte.import}"
types:
  IconifyIcon: "../../types/iconify-icon.md"
functions:
  addCollection: "./add-collection.md"
  addIcon: "./add-icon.md"
  iconExists: "./icon-exists.md"
  iconLoaded: "./icon-exists.md"
  listIcons: "./list-icons.md"
  loadIcons: "./load-icons.md"
  loadIcon: "./load-icon.md"
  getIcon: "./get-icon.md"
  enableCache: "./enable-cache.md"
  disableCache: "./disable-cache.md"
  addAPIProvider: "./add-api-provider.md"
  replaceIDs: "./replace-ids.md"
  buildIcon: "./build-icon.md"
  setFetch: "./set-fetch.md"
  setCustomIconLoader: "./custom-loaders.md"
  setCustomIconsLoader: "./custom-loaders.md"

Iconify for Svelte

include: icon-components/components/intro
replacements:
  - search: React
    replace: Svelte

Please be aware that this component is not designed for server side rendering. If you are using SSR, consider switching to Iconify Icon web component.

Installation

If you are using NPM:

npm install --save-dev @iconify/svelte@2

If you are using Yarn:

yarn add --dev @iconify/svelte@2

Svelte 4

Starting with version 6.0.0 of component, it uses Svelte 5 syntax, which is not compatible with Svelte 4.

If you are using Svelte 4, you need to use version 5 of component:

npm install --save-dev @iconify/svelte@4

or use a web component.

Usage

Install [npm]@iconify/svelte@2 and import component from it (component is exported as default export):

import Icon from "@iconify/svelte";

Then in template use [var]Icon component with icon name as [prop]icon parameter:

<Icon icon="mdi-light:home" />

SvelteKit {#sveltekit}

Component is compatible with SvelteKit. Syntax is the same as with Svelte.

The component does not retrieve icon data until it is mounted. For server side rendering it means generated HTML will not include SVGs, icons will be rendered only on the client side after hydration is complete.

If you do want to render SVGs on the server side, provide icon data as a parameter instead of icon name or use a different icon component.

Properties

You can pass any custom properties to [var]Icon.

Required properties:

include icon-components/component-optional-props

See below for more information on each optional property.

In addition to the properties mentioned above, the icon component accepts any other properties. All other properties will be passed to generated SVG element, so you can do stuff like setting the inline style, add title and so on.

Unlike React component, Svelte component does not support events.

Icon

include: icon-components/components/intro-icon

Color

include: icon-components/components/intro-color
<Icon icon="mdi:home" style="color: red" />

For various ways to set color, see how to change icon color in Iconify for Svelte.

Dimensions

include: icon-components/components/intro-size
<Icon icon="mdi:home" style="font-size: 24px;" />

For various ways to change icon dimensions, see how to change icon dimensions in Iconify for Svelte.

Transformations

include: icon-components/components/intro-transform

For more details see how to transform icon in Iconify for Svelte.

onLoad

include icon-components/components/onload

Functions {#functions}

include: icon-components/components/functions-list/header

Check available icons {#getting-icons}

include: icon-components/components/functions-list/getting-icons

Adding icons {#adding-icons}

include: icon-components/components/functions-list/adding-icons

Custom loaders {#custom-loaders}

include: icon-components/components/functions-list/custom-loaders

Helper functions {#helper}

include: icon-components/components/functions-list/helpers

API functions {#api}

include: icon-components/components/functions-list/api

Internal API functions {#internal}

include: icon-components/components/functions-list/internal
Icon Components

inline

title: Vertical Alignment in Iconify for Svelte

Vertical alignment

This tutorial is part of Iconify for Svelte tutorial.

include icon-components/vertical-align-intro

Inline attribute

include icon-components/components/inline-basic

src: icon-components/common/inline.svelte
demo: true
class: iconify-inline-block

include icon-components/vertical-align-footer

Icon Components

list-icons

title: 'Iconify for Svelte Function: listIcons'

Iconify for Svelte function: listIcons

This tutorial is part of Iconify for Svelte functions tutorial.

include icon-components/functions/list-icons/intro

Usage

include icon-components/functions/list-icons/props

Examples

src: icon-components/common/list-icons.js
replacements:
  - search: react
    replace: svelte

Another example:

src: icon-components/common/list-icons2.js
replacements:
  - search: react
    replace: svelte
Icon Components

load-icon

title: 'Iconify for Svelte Function: loadIcon'
types:
  IconifyIconName: './icon-name.md'
  FullIconifyIcon: '/docs/libraries/utils/full-iconify-icon.md'
functions:
  loadIcons: './load-icons.md'

Iconify for Svelte function: loadIcon

This tutorial is part of Iconify for Svelte functions tutorial.

include icon-components/functions/load-icon/intro

Usage

include icon-components/functions/load-icon/props

IconifyIconName type

include types/iconify-icon-name

Examples

Using [type]Promise syntax:

src: icon-components/common/load-icon.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/svelte'

Async/await syntax:

src: icon-components/common/load-icon-async.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/svelte'

If you want to load multiple icons, see [func]loadIcons().

Icon Components

load-icons

title: 'Iconify for Svelte Function: loadIcons'
functions:
  getIcon: './get-icon.md'
  loadIcon: './load-icon.md'
types:
  IconifyIconName: './icon-name.md'

Iconify for Svelte function: loadIcons

This tutorial is part of Iconify for Svelte functions tutorial.

include icon-components/functions/load-icons/intro

Usage

include icon-components/functions/load-icons/props

Icons list

include icon-components/functions/load-icons/props-icons

Callback

include icon-components/functions/load-icons/props-callback

IconifyIconName type

include types/iconify-icon-name

Examples

Simple callback that loads one icon:

src: icon-components/common/load-icons.js
replacements:
  - search: react
    replace: svelte

Async version of [func]loadIcons():

src: icon-components/common/load-icons-async.js
replacements:
  - search: react
    replace: svelte

Svelte component example

This example renders [html]<slot /> while icon is being loaded, emulating behavior of React component. Due to bug in Svelte, third party components cannot use [html]<slot />, so Svelte component behaves a bit different than other components.

src: icon-components/common/get-icon.svelte

If you want to load only one icon, there is also [func]loadIcon() that is easier to use.

Icon Components

replace-ids

title: 'Iconify for Svelte Function: replaceIDs'
functions:
  getIcon: './get-icon.md'

Iconify for Svelte function: replaceIDs

This tutorial is part of Iconify for Svelte functions tutorial.

include icon-components/functions/replace-ids/intro-component

Usage

include icon-components/functions/replace-ids/props

Example

include icon-components/functions/replace-ids/example-component

src: icon-components/common/replace-ids.js
replacements:
  - search: react
    replace: svelte
Icon Components

set-fetch

title: 'Iconify for Svelte Function: setFetch'

Iconify for Svelte function: setFetch

This tutorial is part of Iconify for Svelte functions tutorial.

include icon-components/functions/set-fetch/intro-component

Why is it needed? {#why}

include: icon-components/functions/set-fetch/why
include: icon-components/functions/set-fetch/nodejs

Usage

include: icon-components/functions/set-fetch/usage

Steps

include: icon-components/functions/set-fetch/component
include: icon-components/functions/set-fetch/bundle
Icon Components

transform

title: Transforming Icon in Iconify for Svelte

Transformations

This tutorial is part of Iconify for Svelte tutorial.

include icon-components/transform-intro

CSS vs Iconify transformations {#css}

include icon-components/transform-compare

Example:

src: icon-components/common/rotate-comparison.svelte
demo: true
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

include icon-components/transform-compare-footer

Flip

include icon-components/components/transform-flip

src: icon-components/common/flip.svelte
hint: Using "flip" attribute
demo: true
extra:
  - src: icon-components/common/flip-alt.svelte
    hint: Using "hFlip" and "vFlip" attributes

Rotation

include icon-components/components/transform-rotate

src: icon-components/common/rotate.svelte
demo: true

Rotate and flip

include icon-components/components/transform-footer

Icon Components

add-api-provider

title: 'Iconify SVG Framework Function: addAPIProvider'

SVG framework function: addAPIProvider

This tutorial is part of Iconify SVG Framework functions tutorial.

include: icon-components/functions/add-api-provider/intro
replacements:
  - search: component
    replace: SVG framework

API providers

include icon-components/api-providers

Usage

include icon-components/functions/add-api-provider/props

Example

Iconify.addAPIProvider('local', {
	// Array of host names
	resources: ['http://localhost:3000'],
});
<span class="iconify" data-icon="@local:material-icons:home"></span>

include icon-components/functions/add-api-provider/footer

Icon Components

add-collection

title: 'Iconify SVG Framework Function: addCollection'
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
functions:
  addIcon: './add-icon.md'

SVG framework function: addCollection

This tutorial is part of Iconify SVG Framework functions tutorial.

include: icon-components/functions/add-collection/intro
replacements:
  - search: component
    replace: SVG framework

Usage

include icon-components/functions/add-collection/props

Examples

Iconify.addCollection({
	prefix: 'custom',
	icons: {
		icon1: {
			body: '<path d="M10 20v-6h4v6h5v-8h3L12 3L2 12h3v8h5z" fill="currentColor"/>',
		},
	},
	width: 24,
	height: 24,
});

Another example:

Iconify.addCollection({
	prefix: 'mdi',
	icons: {
		'account-box': {
			body: '<path d="M6 17c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1H6m9-9a3 3 0 0 1-3 3a3 3 0 0 1-3-3a3 3 0 0 1 3-3a3 3 0 0 1 3 3M3 5v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2z" fill="currentColor"/>',
		},
		'account-cash': {
			body: '<path d="M11 8c0 2.21-1.79 4-4 4s-4-1.79-4-4s1.79-4 4-4s4 1.79 4 4m0 6.72V20H0v-2c0-2.21 3.13-4 7-4c1.5 0 2.87.27 4 .72M24 20H13V3h11v17m-8-8.5a2.5 2.5 0 0 1 5 0a2.5 2.5 0 0 1-5 0M22 7a2 2 0 0 1-2-2h-3c0 1.11-.89 2-2 2v9a2 2 0 0 1 2 2h3c0-1.1.9-2 2-2V7z" fill="currentColor"/>',
		},
		'account': {
			body: '<path d="M12 4a4 4 0 0 1 4 4a4 4 0 0 1-4 4a4 4 0 0 1-4-4a4 4 0 0 1 4-4m0 10c4.42 0 8 1.79 8 4v2H4v-2c0-2.21 3.58-4 8-4z" fill="currentColor"/>',
		},
		'home': {
			body: '<path d="M10 20v-6h4v6h5v-8h3L12 3L2 12h3v8h5z" fill="currentColor"/>',
		},
	},
	width: 24,
	height: 24,
});

Notes

API provider

include icon-components/functions/add-collection/provider

Example:

Iconify.addCollection(
	{
		prefix: 'md',
		icons: {
			test: {
				body: '<path d="M10 20v-6h4v6h5v-8h3L12 3L2 12h3v8h5z" fill="currentColor"/>',
			},
		},
		width: 24,
		height: 24,
	},
	'custom'
);

Code above adds only one icon:

In HTML code this icon can be used like this:

<span class="iconify" data-icon="@custom:md:test"></span>

include icon-components/functions/add-collection/custom

One icon

include icon-components/functions/add-collection/footer

Icon Components

add-icon

title: 'Iconify SVG Framework Function: addIcon'
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
functions:
  addCollection: './add-collection.md'

SVG framework function: addIcon

This tutorial is part of Iconify SVG Framework functions tutorial.

include: icon-components/functions/add-icon/intro
replacements:
  - search: component
    replace: SVG framework

Usage

include icon-components/functions/add-icon/props

Examples

Iconify.addIcon('mdi:account-box', {
	body: '<path d="M6 17c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1H6m9-9a3 3 0 0 1-3 3a3 3 0 0 1-3-3a3 3 0 0 1 3-3a3 3 0 0 1 3 3M3 5v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2z" fill="currentColor"/>',
	width: 24,
	height: 24,
});

Notes

API provider

include icon-components/functions/add-icon/provider

Example:

Iconify.addIcon('@custom:md:test', {
	body: '<path d="M10 20v-6h4v6h5v-8h3L12 3L2 12h3v8h5z" fill="currentColor"/>',
	width: 24,
	height: 24,
});

Code above adds the following icon:

In HTML code this icon can be used like this:

<span class="iconify" data-icon="@custom:md:test"></span>

include icon-components/functions/add-icon/custom

One icon

include icon-components/functions/add-icon/footer

Icon Components

build-icon

title: "Iconify SVG Framework Function: buildIcon"
types:
  IconifyIcon: "/docs/types/iconify-icon.md"
functions:
  renderIcon: "./render-icon.md"
  renderSVG: "./render-svg.md"
  renderHTML: "./render-html.md"
  replaceIDs: "./replace-ids.md"
  getIcon: "./get-icon.md"
  loadIcon: "./load-icon.md"
  iconExists: "./icon-exists.md"
  iconLoaded: "./icon-exists.md"

SVG framework function: buildIcon

This tutorial is part of Iconify SVG Framework functions tutorial.

Function [func]buildIcon() generates data used by [func]renderSVG() and [func]renderHTML() functions.

This function is meant to be used when you generate [tag]svg code.

Usage

include icon-components/functions/build-icon/usage

Result

See [func]renderIcon() function.

Difference from renderIcon

This function is almost identical to [func]renderIcon() with one difference: first parameter is icon data, not icon name.

Why are there two functions? For compatibility with other icon components and with old versions of SVG framework. Other components export only [func]buildIcon(), SVG framework had [func]renderIcon() from old version. Internally, [func]renderIcon() uses same code as [func]buildIcon(), so having both does not increase bundle size by much.

Icon Components

color

title: Changing Icon Color in Iconify SVG Framework

Icon color

This tutorial is part of Iconify SVG Framework tutorial.

You can only change color of monotone icons. Some icons, such as emoji, have a hardcoded palette that cannot be changed.

To change color of a monotone icon simply change text color.

src: icon-components/iconify/index-color.html
css: iconify/index-color.scss
demo: true
class: iconify-index-color

Color only works for icons that do not have a palette. Color in icons that do have a palette, like [icon]noto:paintbrush in an example above, cannot be changed.

Demo breakdown

In demo above some icons have [attr]class="iconify-inline", but in stylesheet they are targetted by [prop].iconify. This requires a small explanation.

When icons are rendered by Iconify SVG Framework, all icons get class [str]iconify, even ones that did not have it. That means if placeholder had [attr]class="iconify-inline", [tag]svg will have [attr]class="iconify iconify-inline" (and few other extra classes). All custom classes will be passed from placeholder to [tag]svg as well.

Why are icons using [attr]class="iconify-inline"? This is covered by inline mode tutorial.

Various ways to set color

You can change color the same way as you would for text.

Example above shows changing color with stylesheet.

You can also change color with inline style:

<span class="iconify" data-icon="ion:umbrella-sharp" style="color: red"></span>

Target specific icon

To target a specific icon, you can:

Target icon by name

.iconify[data-icon='mdi:home'] {
	color: red;
}

This will change color for all icons that have [attr]data-icon="mdi:home" to red.

Target icon by prefix

.iconify--mdi {
	color: red;
}

When SVG Framework renders [tag]svg, it will add current provider and prefix to list of classes. See demo below.

Custom class

You can add custom class to placeholder:

<span class="iconify red-icon" data-icon="mdi:home"></span>

Then you can target icon by that class name:

.red-icon {
	color: red;
}

Example

src: icon-components/iconify/prefix-color.html
hint: 'Placeholder HTML'
extra:
  - src: icon-components/iconify/prefix-color-svg.html
    hint: 'Rendered SVG'
  - src: icon-components/iconify/prefix-color.css

RGBA and HSLA colors {#opacity}

include icon-components/color-rgba

fill and stroke

include icon-components/color-fill

Icon Components

dimensions

title: Changing Icon Dimensions in Iconify SVG Framework

Icon dimensions

This tutorial is part of Iconify SVG Framework tutorial.

By default, icon height is set to [str]"1em", icon width is changed dynamically based on the icon's width to height ratio.

This makes it easy to change icon size by changing [attr]font-size in the stylesheet or in style, just like icon fonts:

src: icon-components/iconify/size-demo.html
css: iconify/size-demo.scss
demo: true
class: iconify2-size-demo

data- attributes {#data}

You can also set dimensions by using [attr]data-width and [attr]data-height attributes. Then [prop]font-size will not have effect on icon, unless you set height in units that are relative to [prop]font-size, such as [str]em.

src: icon-components/iconify/size-demo-data.html
demo: true

In this example, first icon has height of [num]24px, second icon has height of [num]36px ([num]2 * 18px), third icon has height [num]72px.

Keywords "none" and "unset" {#unset}

include: icon-components/components/size-unset
src: icon-components/iconify/size-unset.html
demo: icon-components/common/size-unset.html
class: 'icon-size icon-size--unset'
include: icon-components/components/size-unset-footer

These keywords can only be used with [attr]data-width and [attr]data-height. If you set them as [attr]width or [attr]height, it will not work.

Setting only width or height

In examples above, all icons only use [prop]height.

include icon-components/size-one

Example

include icon-components/size-example

Alignment

include icon-components/align-header

src: icon-components/common/alignment.html
demo: true
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

include icon-components/align-behavior

Icon Components

disable-cache

title: 'Iconify SVG Framework Function: disableCache'
functions:
  enableCache: './enable-cache.md'
  addIcon: './add-icon.md'
  addCollection: './add-collection.md'

SVG framework function: disableCache

This tutorial is part of Iconify SVG Framework functions tutorial.

include: icon-components/functions/cache/intro-disable
replacements:
  - search: component
    replace: SVG framework

Usage

include icon-components/functions/cache/props

Storage types

include icon-components/functions/cache/storage-types

Examples

// Disable caching in localStorage
Iconify.disableCache('local');

Another example:

// Disable all caching
Iconify.disableCache('all');

Notes

include icon-components/functions/cache/notes

Icon Components

enable-cache

title: 'Iconify SVG Framework Function: enableCache'
functions:
  disableCache: './disable-cache.md'
  addIcon: './add-icon.md'
  addCollection: './add-collection.md'

SVG framework function: enableCache

This tutorial is part of Iconify SVG Framework functions tutorial.

include: icon-components/functions/cache/intro-enable
replacements:
  - search: component
    replace: SVG framework

Usage

include icon-components/functions/cache/props-enable

Storage types

include icon-components/functions/cache/storage-types

Examples

// Enable caching in localStorage
Iconify.enableCache('local');

Another example:

// Disable all caching
Iconify.enableCache('all', false);

Notes

include icon-components/functions/cache/notes

Icon Components

functions

title: Iconify SVG Framework Functions
replacements:
  - code: '"2.0.0"'
    value: '"${svg-framework.version.full}"'
  - code: "@iconify/iconify@2"
    value: "${svg-framework.import}"
types:
  IconifyJSON: "../../types/iconify-json.md"
  IconifyIcon: "../../types/iconify-icon.md"
  IconifyInfo: "../../types/iconify-json-metadata.md"
functions:
  addCollection: "./add-collection.md"
  addIcon: "./add-icon.md"
  iconExists: "./icon-exists.md"
  iconLoaded: "./icon-exists.md"
  listIcons: "./list-icons.md"
  getIcon: "./get-icon.md"
  renderSVG: "./render-svg.md"
  renderHTML: "./render-html.md"
  renderIcon: "./render-icon.md"
  replaceIDs: "./replace-ids.md"
  scan: "./scan.md"
  observe: "./observe.md"
  stopObserving: "./stop-observing.md"
  pauseObserver: "./pause-observer.md"
  resumeObserver: "./resume-observer.md"
  loadIcons: "./load-icons.md"
  loadIcon: "./load-icon.md"
  enableCache: "./enable-cache.md"
  disableCache: "./disable-cache.md"
  addAPIProvider: "./add-api-provider.md"
  buildIcon: "./build-icon.md"
  fetFetch: "./set-fetch.md"

SVG framework functions

This tutorial is part of Iconify SVG Framework tutorial.

Iconify SVG framework has many functions that you can use to use the SVG framework in your scripts.

Usage

There are two ways of using SVG framework functions:

Examples of using [func]loadIcon function:

src: icon-components/iconify/load-icon-global.html
title: "Browser:"
replacements:
  - code: "/2/2.0.0/"
    value: "/${svg-framework.version.major}/${svg-framework.version.full}/"
extra:
  - src: icon-components/iconify/load-icon-promise.js
    title: "Node.js:"

Even if you use bundle (method shown in second example), [var]Iconify global is also available because SVG framework exports functions and creates a global variable regardless of how you use it. That means you can use method shown in first example regardless of how you import SVG framework.

Functions

Functions are split in several groups:

Click function name to see more details and examples.

General functions {#general}

In this section there is only one function:

Getting icons {#getting-icons}

include: icon-components/components/functions-list/getting-icons

Adding icons {#adding-icons}

include: icon-components/components/functions-list/adding-icons
replacements:
  - search: "component"
    replace: "SVG framework"

Rendering icons {#render}

Functions that generate SVG or data:

Scanning and observing DOM {#scanner}

SVG framework automatically scans DOM whenever something changes. However, there are some limitations:

In some instances you might want to temporarily disable observer or scan an element that is not part of DOM, such as Shadow DOM. There are functions that you can use:

Helper functions {#helper}

Few helper functions that are exposed because they might be useful when creating things such as icon picker:

API functions {#api}

include: icon-components/components/functions-list/api

Internal API functions {#internal}

include icon-components/components/functions-list/internal-intro

All internal API functions are exposed as properties of [var]Iconify._api object and are available only when API is included:

Icon Components

get-icon

title: 'Iconify SVG Framework Function: getIcon'
types:
  IconifyIcon: '/docs/types/iconify-icon.md'

SVG framework function: getIcon

This tutorial is part of Iconify SVG Framework functions tutorial.

include icon-components/functions/get-icon/intro

Usage

include icon-components/functions/get-icon/props

Examples

src: icon-components/iconify/get-icon.js
extra:
  - src: icon-components/iconify/get-icon.json
    title: 'Result:'

Another example:

src: icon-components/iconify/get-icon2.js
extra:
  - src: icon-components/iconify/get-icon2.json
    title: 'Result:'

Example with bad icon name, returns null:

// null
const data = Iconify.getIcon('no-such-icon');
Icon Components

icon-exists

title: 'Iconify SVG Framework Function: iconExists'

SVG framework function: iconExists

This tutorial is part of Iconify SVG Framework functions tutorial.

include icon-components/functions/icon-exists/intro

Usage

include icon-components/functions/icon-exists/props

Example

function renderLeftArrow() {
	// Check if 'bi:arrow-left' is available
	if (Iconify.iconExists('bi:arrow-left')) {
		// Return HTML for 'bi:arrow-left'
		return Iconify.renderHTML('bi:arrow-left');
	}

	// Load icon. Bad example because this should use a callback to re-render arrow, but
	// this code example is about iconExists(), not loadIcons()
	Iconify.loadIcons(['bi:arrow-left']);

	// Return '<'
	return '&lt;';
}
Icon Components

icon-name

title: 'Iconify SVG Framework Type: IconifyIconName'

IconifyIconName type

include types/iconify-icon-name

Icon name as string

include icon-components/api-providers-short

Examples

src: icon-components/iconify/icon-name.json
title: 'md:home'
hint: Because prefix does not contain hyphen, icon can also be referred as 'md-home'

Another example:

src: icon-components/iconify/icon-name2.json
title: '@local:line-icons:arrow-left'
Icon Components

index

title: Iconify SVG Framework
replacements:
  - code: '60k'
    value: '${counters.icons-short}'
  - code: '@iconify/iconify@2'
    value: '${svg-framework.import}'
functions:
  buildIcon: './build-icon.md'
  setFetch: './set-fetch.md'

Iconify SVG framework

include notices/iconify2

Iconify SVG framework is an easy-to-use JavaScript library that renders icons.

It combines the pixel-perfect rendering of SVG with ease of use of glyph fonts while offering more choice than any glyph font or SVG framework.

Unlike icon fonts, the Iconify SVG framework only loads icons that are used on the current page, so visitors do not waste bandwidth loading hundreds or thousands of icons just to show a few icons.

Iconify SVG framework was designed to be as easy to use as possible. You can change icon dimensions and color with CSS, just like icon fonts.

Usage

Adding icons to the HTML document is easy:

Add script tag to include the Iconify SVG framework. You can add it in the head section (before [tag]</head>) or at the end of page before [tag]</body>:

src: icon-components/iconify/script.html
replacements:
  - code: '/2/2.0.0/'
    value: '/${svg-framework.version.major}/${svg-framework.version.full}/'

To add an icon, write placeholder [tag]span (or it could be any other inline DOM element):

src: icon-components/iconify/index-sample0.html
demo: true
demoFirst: false

To change an icon, write a different icon name in the [attr]data-icon attribute instead of [str]"fa-solid:home".

Look in icon collections to find icons. Click an icon to see HTML code for that icon.

Importing SVG framework

You can also import Iconify SVG framework in other script and bundle it with your code. This is useful if you are using tools like WebPack or Rollup.js to build your project.

Install [npm]@iconify/iconify@2 as dependency and import it in your project:

import Iconify from '@iconify/iconify';

Usage without API

Iconify SVG framework retrieves icon data from Iconify API. That makes it very easy to use because developer does not need to prepare the icon data. Downside is, visitor must be online to retrieve icon data.

How does it work?

Iconify SVG framework works by locating icon placeholders, retrieving icon name from placeholder, retrieving icon data from Iconify API, then replacing the placeholder with SVG. This is done very quickly in a fraction of a second.

What are the advantages of this approach?

What are the disadvantages?

If you need to render icons without relying on Iconify API, use a different icon component.

Icon syntax

An element must have [tag]span or [tag]i tag.

For the Iconify SVG framework to treat the element as icon placeholder, the element must have [str]iconify or [str]iconify-inline among the list of classes.

Element also must have a [prop]data-icon attribute with icon name as value.

src: icon-components/iconify/index-sample1.html
demo: true
demoFirst: false

Icon name syntax is [attr]data-icon="prefix:icon-name" or [attr]data-icon="prefix-icon-name". Second syntax can be used if prefix does not contain [str]"-", it is kept for compatibility with icon fonts.

For example, [attr]data-icon="fa-arrow-left" and [attr]data-icon="fa:arrow-left" are identical (both have a prefix [str]"fa"), but [attr]data-icon="flat-color-icons:voice-presentation" and [attr]data-icon="flat-color-icons-voice-presentation" are not the same (first has a prefix [str]"flat-color-icons", second has a prefix [str]"flat" that does not exist).

Color

You can only change color of monotone icons. Some icons, such as emoji, have a hardcoded palette that cannot be changed.

To add color to the monotone icon simply change text color.

<span class="iconify" data-icon="ion:umbrella-sharp" style="color: red"></span>

For various ways to set color, see changing icon color tutorial.

Dimensions

By default, icon height is set to [str]"1em", icon width is changed dynamically based on the icon's width to height ratio.

This makes it easy to change icon size by changing [attr]font-size in the stylesheet, just like icon fonts:

<span
	class="iconify"
	data-icon="cil:locomotive"
	style="font-size: 24px;"
></span>

For various ways to change icon dimensions, see changing icon dimensions tutorial.

Transformations

An icon can be rotated and flipped horizontally and/or vertically. All transformations are done relative to the center of the icon.

These are not CSS transformations, transformations are applied inside SVG.

For more details see icon transformations tutorial.

Functions {#functions}

Iconify SVG framework offers many functions, which developers can use to control SVG framework:

For more details see Iconify SVG framework functions.

Server side rendering {#ssr}

SVG Framework can be used in Node.js scripts, but because there is no DOM, it can be used only to generate data using functions such as [func]buildIcon().

include: icon-components/functions/set-fetch/nodejs

How to solve this problem?

include: icon-components/functions/set-fetch/svg-framework
Icon Components

inline

title: Vertical Alignment in Iconify SVG Framework

Vertical alignment

This tutorial is part of Iconify SVG Framework tutorial.

include icon-components/vertical-align-intro

Inline attribute

To add [prop]vertical-align to icon, there are has several options:

src: icon-components/common/inline.html
demo: true
class: iconify-inline-block

include icon-components/vertical-align-footer

Icon Components

list-icons

title: 'Iconify SVG Framework Function: listIcons'

SVG framework function: listIcons

This tutorial is part of Iconify SVG Framework functions tutorial.

include icon-components/functions/list-icons/intro

Usage

include icon-components/functions/list-icons/props

Examples

// List all icons
console.log(Iconify.listIcons());

Another example:

// List all loaded Material Design Icons
console.log(Iconify.listIcons('', 'mdi'));
// ["mdi:alert", "mdi:home", "mdi:account-box-outline", "mdi:eyedropper", "mdi:account-off", "mdi:account", "mdi:account-box", "mdi:account-cash"]
Icon Components

load-icon

title: 'Iconify SVG Framework Function: loadIcon'
functions:
  scan: './scan.md'
  loadIcons: './load-icons.md'
types:
  IconifyIconName: './icon-name.md'
  FullIconifyIcon: '/docs/libraries/utils/full-iconify-icon.md'

SVG framework function: loadIcon

This tutorial is part of Iconify SVG Framework functions tutorial.

include: icon-components/functions/load-icon/intro
replacements:
  - search: 'component'
    replace: 'SVG framework'

Usage

include icon-components/functions/load-icon/props

IconifyIconName type

include types/iconify-icon-name

Examples

Using [type]Promise syntax:

src: icon-components/iconify/load-icon-global.html
replacements:
  - code: '/2/2.0.0/'
    value: '/${svg-framework.version.major}/${svg-framework.version.full}/'

Async/await syntax:

src: icon-components/iconify/load-icon-await.js

If you want to load multiple icons, see [func]loadIcons().

Icon Components

load-icons

title: 'Iconify SVG Framework Function: loadIcons'
functions:
  scan: './scan.md'
  getIcon: './get-icon.md'
  loadIcon: './load-icon.md'
types:
  IconifyIconName: './icon-name.md'

SVG framework function: loadIcons

This tutorial is part of Iconify SVG Framework functions tutorial.

include icon-components/functions/load-icons/intro

Usage

include icon-components/functions/load-icons/props

Icons list

include icon-components/functions/load-icons/props-icons

Callback

include icon-components/functions/load-icons/props-callback

IconifyIconName type

include types/iconify-icon-name

Examples

Simple callback that loads one icon:

const iconName = 'mdi:home';
Iconify.loadIcons([iconName], (loaded, missing, pending, unsubscribe) => {
	if (loaded.length) {
		console.log(
			`Icon ${iconName} have been loaded and is ready to be renderered.`
		);
		return;
	}

	if (missing.length) {
		console.log(`Icon ${iconName} does not exist.`);
		return;
	}

	if (pending.length) {
		// Pending icons list in this example is empty.
		// If you call loadIcons() with multiple icons, pending list might not be empty, but for one icon it is always empty.
		//
		// Callback is called when something changes, with 1 icon there can only be 2 type of changes: icon has loaded or icon is missing.
	}
});

Async version of [func]loadIcons():

/**
 * Function to load icons, returns Promise
 */
function loadIcons(icons) {
	return new Promise((fulfill, reject) => {
		Iconify.loadIcons(icons, (loaded, missing, pending, unsubscribe) => {
			if (pending.length) {
				// Icons are pending, wait for all to load/fail
				return;
			}
			if (missing.length) {
				reject({
					loaded,
					missing,
				});
			} else {
				fulfill({
					loaded,
				});
			}
		});
	});
}

/**
 * Usage example in async function
 */
async function test() {
	await loadIcons(['jam:info', 'cil:locomotive', 'cil:paper-plane']).catch(
		(err) => {
			console.error('Failed to load icons:', err.missing);
		}
	);

	// Do stuff with loaded icons
	console.log('Loaded!');
}
test();

If you want to load only one icon, there is also [func]loadIcon() that is easier to use.

Icon Components

observe

title: 'Iconify SVG Framework Function: observe'
functions:
  scan: './scan.md'
  stopObserving: './stop-observing.md'
  pauseObserver: './pause-observer.md'
  resumeObserver: './resume-observer.md'
  renderSVG: './render-svg.md'
  renderHTML: './render-html.md'
  loadIcons: './load-icons.md'

SVG framework function: observe

This tutorial is part of Iconify SVG Framework functions tutorial.

Function [func]observe() tells the SVG framework to watch an HTML element for icon placeholders, so the SVG framework could find them and replace with [tag]svg.

SVG framework automatically watches [prop]document.body, so no need to call this function for [prop]documet.body.

When to use this function:

Usage

Function has the following parameter:

Example

// Create element.
const node = document.createElement('div');

// Tell SVG framework to watch element.
Iconify.observe(node);

// Add icon 1 second later - it will be replaced with <svg>
setTimeout(() => {
	node.innerHTML =
		'Home icon: <span class="iconify" data-icon="mdi:home"></span>';
}, 1000);

Another example:

// Create element, start watching it.
function createNode() {
	let clicked = false;

	// Create element, set content.
	const node = document.createElement('a');
	node.innerHTML =
		'<span class="iconify" data-icon="carbon:circle-dash"></span>';

	// Change icon on click.
	node.addEventListener('click', () => {
		clicked = !clicked;
		node
			.querySelector('.iconify')
			.setAttribute(
				'data-icon',
				clicked ? 'carbon:circle-filled' : 'carbon:circle-dash'
			);
	});

	// Observe changes.
	// This is not needed if you are adding element to document.body because document.body is already
	// automatically watched. Use this if element is part of Shadow DOM or some other custom elements tree.
	Iconify.observe(node);

	return node;
}

// Stop watching element.
// Always stop observing element if you no longer need it!
// SVG framework doesn't know if you still need an element.
function removeNode(node) {
	Iconify.stopObserving(node);
}

Notes

Icon Components

optimizations

title: Iconify SVG Framework Optimizations
replacements:
  - code: '22kb'
    value: '${svg-framework.size}'

SVG framework optimizations

This tutorial is part of Iconify SVG Framework tutorial.

This tutorial has several parts:

Where to place script tag? {#header-vs-footer}

Most site optimization tutorials tell you that you should put scripts in footer before [tag]</body>. What about Iconify? You can put Iconify script in head section (between [tag]<head> and [tag]</head>) or in footer before [tag]</body>.

So what's the difference?

Putting Iconify in footer {#script-footer}

However, it also means icon placeholders won't be replaced until entire page has been loaded. Iconify cannot start doing its thing until it has loaded.

Putting Iconify in head section {#script-header}

Iconify SVG framework is rather small (about 22kb uncompressed), delivered from fast CloudFlare CDN. It takes fraction of second to load.

Benefit of placing Iconify script in head section is, it can start replacing icons right away. That means, if you have a large page, icons will be replaced as soon as part of document loads instead of waiting for an entire document to load.

Conclusion {#script-conclusion}

There are pros and cons for each method. You should decide for yourself instead of blindly relying on recommendations from online website checkers. Online website checkers don't know what script does and how it works, so they always recommend putting all scripts in footer.

If your pages are small, probably better to put script in footer before [tag]</body>. For example, this website has it in footer.

If your pages are large, dynamically generated, such as forum pages, it might be better to put script in head section. Forum pages might take several seconds to load, by placing script in head section, you make sure visitors see icons as soon as possible.

If you are experiencing flickering during load (page loads, then renders, then icons are replaced), you probably should move Iconify SVG framework script to head section.

How to optimize loading icons {#loading}

Iconify SVG framework is fast, but you can make it even faster by helping Iconify figure out what icons to load.

There are several ways to improve icon loading:

Preloading icons

If your page is likely to display additional icons after initial page load, such as AJAX forms or React/Angular application, you can tell Iconify SVG framework to pre-load those icons. Then, when your script will display those icons, Iconify would already have data for those icons retrieved from API.

This also helps to reduce number of API queries. Loading icons in bulk is faster than loading them one by one.

To preload icons add this code anywhere after including Iconify script:

src: icon-components/iconify/preload.html

Argument to [func]loadIcons is an array of icons you want to load.

To use this function, make sure either Iconify is placed in footer before [tag]</body> or put it in a bundle with SVG framework. Otherwise, SVG framework might be loaded faster than your script, scan DOM and get shorter list of icons to retrieve, splitting it into multiple API queries.

Icon Components

pause-observer

title: 'Iconify SVG Framework Function: pauseObserver'
functions:
  scan: './scan.md'
  observe: './observe.md'
  stopObserving: './stop-observing.md'
  resumeObserver: './resume-observer.md'

SVG framework function: pauseObserver

This tutorial is part of Iconify SVG Framework functions tutorial.

Function [func]pauseObserver() tells SVG framework to temporarily stop watching HTML element for icon placeholders.

Use this function when you need to do a lot of DOM manipulation and you want to prevent SVG framework from scanning DOM until you resume observing using [func]resumeObserver().

Usage

Function has the following optional parameter:

Example

// Pause observer
Iconify.pauseObserver();

// Do some heavy DOM manipulation
// ...
// ...

// Resume observer
Iconify.resumeObserver();

Notes

Icon Components

render-html

title: 'Iconify SVG Framework Function: renderHTML'
functions:
  renderSVG: './render-svg.md'
  renderIcon: './render-icon.md'

SVG framework function: renderHTML

This tutorial is part of Iconify SVG Framework functions tutorial.

Function [func]renderHTML() generates HTML code for icon.

Usage

Function has the following parameters:

Function returns [type]string, null if icon is not available.

Examples

if (Iconify.iconExists('mdi:home')) {
	node.innerHTML = Iconify.renderHTML('mdi:home');
}

Another example:

const node = document.createElement('div');
node.innerHTML = Iconify.renderHTML('bi:stopwatch', {
	rotate: 1,
	height: 'auto',
});

Customizations

Second parameter is optional icon customizations. Do not confuse it with placeholder [attr]data- attributes.

Available customizations:

include icon-components/customisations

For more details about dimensions and alignment see icon dimensions documentation.

For more details about transformations see icon transformations documentation.

Rendering SVG

This function creates [tag]string. If you want to create [tag]svg element, use [func]renderSVG() instead.

Icon Components

render-icon

title: "Iconify SVG Framework Function: renderIcon"
functions:
  renderSVG: "./render-svg.md"
  renderHTML: "./render-html.md"
  replaceIDs: "./replace-ids.md"
  getIcon: "./get-icon.md"
  loadIcon: "./load-icon.md"
  iconExists: "./icon-exists.md"
  iconLoaded: "./icon-exists.md"

SVG framework function: renderIcon

This tutorial is part of Iconify SVG Framework functions tutorial.

Function [func]renderIcon() generates data used by [func]renderSVG() and [func]renderHTML() functions.

This function is meant to be used when you generate [tag]svg element yourself. For example, if it is generated by some component.

Usage

Function has the following parameters:

Function returns [type]object containing icon data, null if icon is not available.

Result

include: icon-components/functions/build-icon/result
replacements:
  - search: "icon component"
    replace: "SVG framework"

Change IDs! {#important}

Use function [func]replaceIDs() when generating icons using data provided by this function.

It will make sure elements inside each icon have unique IDs.

Examples

src: icon-components/iconify/render-icon.js
extra:
  - src: icon-components/iconify/render-icon.json
    title: "Result:"

Another example:

// Get icon data
const icon = Iconify.renderIcon("carbon:deploy");

// Create element
const svg = document.createElement("svg");
const svgDefaults: IconifySVGProps = {
  xmlns: "http://www.w3.org/2000/svg",
  "xmlns:xlink": "http://www.w3.org/1999/xlink",
  "aria-hidden": true,
  focusable: false,
  role: "img",
};
Object.keys(svgDefaults).forEach((attr) => {
  svg.setAttribute(attr, svgDefaults[attr]);
});
Object.keys(icon.attributes).forEach((attr) => {
  svg.setAttribute(attr, icon.attributes[attr]);
});

// Set content
svg.innerHTML = Iconify.replaceIDs(icon.body);

Customizations

Second parameter is optional icon customizations. Do not confuse it with placeholder [attr]data- attributes.

Available customizations:

include icon-components/customisations

For more details about dimensions and alignment see icon dimensions documentation.

For more details about transformations see icon transformations documentation.

Rendering SVG or HTML

This function creates [type]object. If you want to create [tag]svg element, use [func]renderSVG() instead. If you want to get HTML [type]string, use [func]renderHTML() instead.

Icon Components

render-svg

title: 'Iconify SVG Framework Function: renderSVG'
functions:
  renderHTML: './render-html.md'
  renderIcon: './render-icon.md'

SVG framework function: renderSVG

This tutorial is part of Iconify SVG Framework functions tutorial.

Function [func]renderSVG() creates [tag]svg element.

Usage

Function has the following parameters:

Function returns [tag]svg element, null if icon is not available.

Examples

src: icon-components/iconify/render-svg.js
demo: true
extra:
  - src: icon-components/iconify/render-svg.html
    hint: 'Generated HTML'

Another example:

const node = document.createElement('div');
const icon = Iconify.renderSVG('bi:stopwatch', { rotate: 1, height: 'auto' });
node.appendChild(icon);

Customizations

Second parameter is optional icon customizations. Do not confuse it with placeholder [attr]data- attributes.

Available customizations:

include icon-components/customisations

For more details about dimensions and alignment see icon dimensions documentation.

For more details about transformations see icon transformations documentation.

Rendering HTML

This function creates [tag]svg element. If you want to get [type]string, use [func]renderHTML() instead.

Icon Components

replace-ids

title: 'Iconify SVG Framework Function: replaceIDs'
functions:
  renderSVG: './render-svg.md'
  renderHTML: './render-html.md'
  renderIcon: './render-icon.md'
  getIcon: './get-icon.md'

SVG framework function: replaceIDs

This tutorial is part of Iconify SVG Framework functions tutorial.

Function [func]replaceIDs() finds IDs in SVG and replaces them with unique random IDs.

This function is meant to be used when you generate [tag]svg element yourself using data provided by [func]renderIcon() or [func]getIcon(). For example, if icon is generated by some component.

Usage

include icon-components/functions/replace-ids/props

Example

// Get icon data
const icon = Iconify.renderIcon('carbon:deploy', {
	height: 'auto',
});

// Create element
const svg = document.createElement('svg');
const svgDefaults: IconifySVGProps = {
	'xmlns': 'http://www.w3.org/2000/svg',
	'xmlns:xlink': 'http://www.w3.org/1999/xlink',
	'aria-hidden': true,
	'focusable': false,
	'role': 'img',
};
Object.keys(svgDefaults).forEach((attr) => {
	svg.setAttribute(attr, svgDefaults[attr]);
});
Object.keys(icon.attributes).forEach((attr) => {
	svg.setAttribute(attr, icon.attributes[attr]);
});

// Set content
svg.innerHTML = Iconify.replaceIDs(icon.body);
Icon Components

resume-observer

title: 'Iconify SVG Framework Function: resumeObserver'
functions:
  scan: './scan.md'
  observe: './observe.md'
  stopObserving: './stop-observing.md'
  pauseObserver: './pause-observer.md'

SVG framework function: resumeObserver

This tutorial is part of Iconify SVG Framework functions tutorial.

Function [func]resumeObserver() tells SVG framework to continue watching HTML element for icon placeholders that was paused using [func]pauseObserver().

Usage

Function has the following optional parameter:

Example

// Pause observer
Iconify.pauseObserver();

// Do some heavy DOM manipulation
// ...
// ...

// Resume observer
Iconify.resumeObserver();

Notes

Icon Components

scan

title: 'Iconify SVG Framework Function: scan'
functions:
  observe: './observe.md'
  stopObserving: './stop-observing.md'
  pauseObserver: './pause-observer.md'
  resumeObserver: './resume-observer.md'

SVG framework function: scan

This tutorial is part of Iconify SVG Framework functions tutorial.

Function [func]scan() scans document for icon placeholders and replaces placeholders with icons.

SVG framework automatically watches [prop]document.body and scans DOM after every change, so no need to use this function after you are changing DOM.

When to use this function:

If you want SVG framework to watch custom root element for changes, do not use this function, use [func]observe() instead. This function stops watching element when all placeholders have been replaced, [func]observe() continues to watch element until you tell it to stop using [func]stopObserving().

Usage

Function has the following optional parameter:

Example

const node = document.createElement('div');
node.innerHTML =
	'Home icon: <span class="iconify" data-icon="mdi:home"></span>';
Iconify.scan(node);

Notes

Icon Components

set-fetch

title: 'Iconify SVG Framework Internal Function: setFetch'

SVG framework internal function: setFetch

This tutorial is part of Iconify SVG Framework functions tutorial.

include icon-components/functions/set-fetch/intro-component

Why is it needed? {#why}

include: icon-components/functions/set-fetch/why
replacements:
  - search: 'icon component'
    replace: 'SVG framework'
include: icon-components/functions/set-fetch/nodejs

Usage

include: icon-components/functions/set-fetch/usage

Steps

include: icon-components/functions/set-fetch/svg-framework
Icon Components

stop-observing

title: 'Iconify SVG Framework Function: stopObserving'
functions:
  scan: './scan.md'
  observe: './observe.md'
  pauseObserver: './pause-observer.md'
  resumeObserver: './resume-observer.md'

SVG framework function: stopObserving

This tutorial is part of Iconify SVG Framework functions tutorial.

Function [func]stopObserving() tells SVG framework to stop watching HTML element for icon placeholders.

When to use this function:

Usage

Function has the following parameter:

Example

// Create element, start watching it.
function createNode() {
	let clicked = false;

	// Create element, set content.
	const node = document.createElement('a');
	node.innerHTML =
		'<span class="iconify" data-icon="carbon:circle-dash"></span>';

	// Change icon on click.
	node.addEventListener('click', () => {
		clicked = !clicked;
		node
			.querySelector('.iconify')
			.setAttribute(
				'data-icon',
				clicked ? 'carbon:circle-filled' : 'carbon:circle-dash'
			);
	});

	// Observe changes.
	// This is not needed if you are adding element to document.body because document.body is already
	// automatically watched. Use this if element is part of Shadow DOM or some other custom elements tree.
	Iconify.observe(node);

	return node;
}

// Stop watching element.
// Always stop observing element if you no longer need it!
// SVG framework doesn't know if you still need an element.
function removeNode(node) {
	Iconify.stopObserving(node);
}
Icon Components

transform

title: Transforming Icons in Iconify SVG Framework

Transformations

This tutorial is part of Iconify SVG Framework tutorial.

include icon-components/transform-intro

CSS vs Iconify transformations {#css}

include icon-components/transform-compare

Example:

src: icon-components/common/rotate-comparison.html
demo: true
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

In example above, first icon is rotated using [attr]data-rotate attribute, second icon is rotated using CSS. First icon kept its 1em height, second icon became taller than it should be.

Sometimes you do want behaviour that CSS transformations provide. Then you can still use CSS transformations by adding it to inline style.

Flip

You can flip icon horizontally and/or vertically.

To do that, add [attr]data-flip attribute with comma separated values. Possible values:

Example:

src: icon-components/common/flip.html
demo: true

Rotation

You can rotate icon by [num]90, [num]180 and [num]270 degrees.

To do that, add [attr]data-rotate attribute. Possible values:

Example:

src: icon-components/common/rotate.html
demo: true

Rotate and flip

You can use both rotation and flip on an icon. The icon is flipped first, then rotated.

Icon Components

add-api-provider

title: 'Iconify for Vue Function: addAPIProvider'

Iconify for Vue function: addAPIProvider

This tutorial is part of Iconify for Vue functions tutorial.

include icon-components/functions/add-api-provider/intro

API providers

include icon-components/api-providers

Usage

include icon-components/functions/add-api-provider/props

Example

src: icon-components/common/add-api-provider.vue

include icon-components/functions/add-api-provider/footer

Icon Components

add-collection

title: 'Iconify for Vue Function: addCollection'
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
functions:
  addIcon: './add-icon.md'

Iconify for Vue function: addCollection

This tutorial is part of Iconify for Vue functions tutorial.

include icon-components/functions/add-collection/intro

Usage

include icon-components/functions/add-collection/props

Examples

src: icon-components/common/add-collection.js
replacements:
  - search: react
    replace: vue
src: icon-components/common/add-collection2.js
replacements:
  - search: react
    replace: vue

include icon-components/functions/add-collection/notes

API provider

include icon-components/functions/add-collection/provider

Example:

src: icon-components/common/add-collection3.js
replacements:
  - search: react
    replace: vue

Code above adds only one icon:

In component template this icon can be used like this:

<Icon icon="@custom:md:test" />

include icon-components/functions/add-collection/custom

One icon

include icon-components/functions/add-collection/footer

Icon Components

add-icon

title: 'Iconify for Vue Function: addIcon'
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
functions:
  addCollection: './add-collection.md'

Iconify for Vue function: addIcon

This tutorial is part of Iconify for Vue functions tutorial.

include icon-components/functions/add-icon/intro

Usage

include icon-components/functions/add-icon/props

Examples

src: icon-components/common/add-icon.js
replacements:
  - search: react
    replace: vue

include icon-components/functions/add-icon/notes

API provider

include icon-components/functions/add-icon/provider

Example:

src: icon-components/common/add-icon2.js
replacements:
  - search: react
    replace: vue

Code above adds the following icon:

In component template this icon can be used like this:

<Icon icon="@custom:md:test" />

include icon-components/functions/add-icon/custom

One icon

include icon-components/functions/add-icon/footer

Icon Components

build-icon

title: "Iconify for Vue Function: renderSVG"
types:
  IconifyIcon: "/docs/types/iconify-icon.md"
functions:
  replaceIDs: "./replace-ids.md"
  getIcon: "./get-icon.md"
  loadIcon: "./load-icon.md"
  iconLoaded: "./icon-exists.md"

Iconify for Vue function: buildIcon

This tutorial is part of Iconify for Vue functions tutorial.

include icon-components/functions/build-icon/intro-component

Usage

include icon-components/functions/build-icon/usage

Result

include icon-components/functions/build-icon/result

Customizations

Second parameter is optional icon customizations. Available customizations:

include icon-components/customisations

For more details about dimensions see icon dimensions documentation.

For more details about transformations see icon transformations documentation.

Example

src: icon-components/common/build-icon.js
replacements:
  - search: "@iconify/svelte"
    replace: "@iconify/vue"
extra:
  - src: icon-components/common/build-icon.json
    title: "Result:"
Icon Components

color

title: Changing Icon Color in Iconify for Vue

Icon color

This tutorial is part of Iconify for Vue tutorial.

include: icon-components/components/color-intro
src: icon-components/common/color.vue
css: components/color.scss
demo: true
class: components-color
include: icon-components/components/color-intro2

RGBA and HSLA colors {#opacity}

include icon-components/color-rgba

fill and stroke

include icon-components/color-fill

Icon Components

custom-loaders

title: "Iconify for Vue Functions: setCustomIconLoader and setCustomIconsLoader"
types:
  IconifyJSON: "../../types/iconify-json.md"
  IconifyIcon: "../../types/iconify-icon.md"
functions:
  loadIcon: "./load-icon.md"

Custom icon loaders

This tutorial is part of Iconify for Vue tutorial.

include icon-components/functions/set-loaders/intro

Usage

include icon-components/functions/set-loaders/props

Example

src: icon-components/common/set-loader.js
replacements:
  - search: "@iconify/react"
    replace: "@iconify/vue"

Make sure loader is set before any icons are rendered, otherwise component might attempt to load icon from API and fail to render it.

Icon Components

dimensions

title: Changing Icon Dimensions in Iconify for Vue

Icon dimensions

This tutorial is part of Iconify for Vue tutorial.

include: icon-components/components/size-intro
src: icon-components/common/size.vue
css: components/size.scss
demo: true
class: components-size

If you want to control icon size with [prop]width and [prop]height in CSS, see how to remove icon dimensions section below.

Units

include: icon-components/components/size-units
<Icon icon="mdi:home" :height="24" />
<Icon icon="mdi:home" height="24" />
<Icon icon="mdi:home" height="24px" />

Keyword "auto" {#auto}

include: icon-components/components/size-auto
<Icon icon="mdi:home" height="auto" />

Keywords "none" and "unset" {#unset}

include: icon-components/components/size-unset
src: icon-components/common/size-unset.vue
demo: true
class: 'icon-size icon-size--unset'
include: icon-components/components/size-unset-footer

Setting only width or height

In an example above, all icons only use [prop]height.

include icon-components/size-one

Example

include icon-components/size-example

Alignment

include icon-components/align-header

src: icon-components/common/alignment.vue
demo: true
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

include icon-components/align-behavior

Icon Components

disable-cache

title: "Iconify for Vue Function: disableCache"
functions:
  enableCache: "./enable-cache.md"
  addIcon: "./add-icon.md"
  addCollection: "./add-collection.md"

Iconify for Vue function: disableCache

This tutorial is part of Iconify for Vue functions tutorial.

include icon-components/functions/cache/deprecated

include icon-components/functions/cache/intro-disable

Usage

include icon-components/functions/cache/props

Storage types

include icon-components/functions/cache/storage-types

Examples

src: icon-components/common/disable-cache.js
replacements:
  - search: react
    replace: vue

Another example:

src: icon-components/common/disable-cache2.js
replacements:
  - search: react
    replace: vue

Notes

include icon-components/functions/cache/notes

Icon Components

enable-cache

title: "Iconify for Vue Function: enableCache"
functions:
  disableCache: "./disable-cache.md"
  addIcon: "./add-icon.md"
  addCollection: "./add-collection.md"

Iconify for Vue function: enableCache

This tutorial is part of Iconify for Vue functions tutorial.

include icon-components/functions/cache/deprecated

include icon-components/functions/cache/intro-enable

Usage

include icon-components/functions/cache/props

Storage types

include icon-components/functions/cache/storage-types

Example

src: icon-components/common/enable-cache.js
replacements:
  - search: react
    replace: vue

Notes

include icon-components/functions/cache/notes

Icon Components

get-icon

title: 'Iconify for Vue Function: getIcon'
types:
  IconifyIcon: '/docs/types/iconify-icon.md'

Iconify for Vue function: getIcon

This tutorial is part of Iconify for Vue functions tutorial.

include icon-components/functions/get-icon/intro

Usage

include icon-components/functions/get-icon/props

Examples

src: icon-components/common/get-icon.js
extra:
  - src: icon-components/iconify/get-icon.json
    title: 'Result:'
replacements:
  - search: react
    replace: vue

Another example:

src: icon-components/common/get-icon2.js
extra:
  - src: icon-components/iconify/get-icon2.json
    title: 'Result:'
replacements:
  - search: react
    replace: vue

Example with bad icon name, returns null:

src: icon-components/common/get-icon-null.js
replacements:
  - search: react
    replace: vue
Icon Components

icon-exists

title: "Iconify for Vue Function: iconLoaded"
functions:
  getIcon: "./get-icon.md"
  loadIcons: "./load-icons.md"

Iconify for Vue function: iconLoaded

This tutorial is part of Iconify for Vue functions tutorial.

include icon-components/functions/icon-loaded/intro

Usage

include icon-components/functions/icon-loaded/props

Example

import { iconLoaded } from "@iconify/vue";

const icon = "bi:arrow-left";
console.log(`Is ${icon} available?`, iconLoaded(icon) ? "yes" : "no");

This example dynamically loads icon data and renders [html]<slot /> while icon is being loaded. It is redundant because Vue component already does that, but it is used to show how to use [func]iconLoaded() and [func]loadIcons(), though instead of [func]iconLoaded() it is better done with [func]getIcon().

import { Icon, iconLoaded, loadIcons } from "@iconify/vue";
import { h, defineComponent, ref } from "vue";

export default defineComponent({
  components: {
    Icon,
  },
  props: ["icon"],
  setup() {
    // Variable to store function to cancel loading
    const loader = ref(null);

    // Icon status
    const loaded = ref(null);

    // Function to check if icon data is available
    const check = (icon: string) => {
      const isLoaded = (loaded.value = iconLoaded(icon));

      // Cancel old loder
      if (loader.value) {
        loader.value();
        loader.value = null;
      }

      if (!isLoaded) {
        loader.value = loadIcons([icon], () => {
          loaded.value = iconLoaded(icon);
        });
      }
    };
    return {
      loader,
      loaded,
      check,
    };
  },
  watch: {
    icon: {
      immediate: true,
      handler(value) {
        // Check new value
        this.check(value);
      },
    },
  },
  // Stop loading
  unmounted() {
    const loader = this.loader.value;
    if (loader) {
      loader();
    }
  },
  render() {
    const loaded = this.loaded;
    if (loaded) {
      return h(Icon, {
        icon: this.icon,
      });
    }
    return this.$slots.default ? this.$slots.default() : null;
  },
});

Legacy

include icon-components/functions/icon-loaded/legacy

Icon Components

icon-name

title: 'Iconify Type: IconifyIconName'

IconifyIconName type

include types/iconify-icon-name

API providers

include icon-components/api-providers-short

Examples

src: icon-components/iconify/icon-name.json
title: 'md:home'
hint: Because prefix does not contain hyphen, icon can also be referred as 'md-home'

Another example:

src: icon-components/iconify/icon-name2.json
title: '@local:line-icons:arrow-left'
Icon Components

index

title: Iconify for Vue
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "80+"
    value: "${counters.sets}+"
  - code: "@iconify/vue@3"
    value: "${vue.import}"
types:
  IconifyIcon: "/docs/types/iconify-icon.md"
functions:
  addCollection: "./add-collection.md"
  addIcon: "./add-icon.md"
  iconExists: "./icon-exists.md"
  listIcons: "./list-icons.md"
  loadIcons: "./load-icons.md"
  loadIcon: "./load-icon.md"
  getIcon: "./get-icon.md"
  enableCache: "./enable-cache.md"
  disableCache: "./disable-cache.md"
  addAPIProvider: "./add-api-provider.md"
  replaceIDs: "./replace-ids.md"
  buildIcon: "./build-icon.md"
  setFetch: "./set-fetch.md"
  setCustomIconLoader: "./custom-loaders.md"
  setCustomIconsLoader: "./custom-loaders.md"

Iconify for Vue

include: icon-components/components/intro
replacements:
  - search: React
    replace: Vue

Please be aware that this component is not designed for server side rendering. If you are using SSR, consider switching to Iconify Icon web component.

Installation

If you are using NPM:

npm install --save-dev @iconify/vue@3

If you are using Yarn:

yarn add --dev @iconify/vue@3

Usage

Install [npm]@iconify/vue@3 and import component from it (component is exported as named export):

import { Icon } from "@iconify/vue";

Then in template use [var]Icon component with icon name as [prop]icon parameter:

<Icon icon="mdi-light:home" />

Nuxt.js {#ssr}

Component is compatible with Nuxt.js.

The component does not retrieve icon data until it is mounted. For server side rendering it means generated HTML will not include SVGs, icons will be rendered only on the client side after hydration is complete.

If you do want to render SVGs on the server side, provide icon data as a parameter instead of icon name or use a different icon component.

SSR attribute

In version 4.1.2 new boolean attribute was added: [prop]ssr.

If enabled, it will render icon immediately:

<Icon icon="mdi:home" :ssr="true" />

It is safe to use without SSR because there is no hydration to break.

If you are using SSR, such as Nuxt, make sure icon data is available on both server and client sides.

Properties

You can pass any custom properties to component.

Required properties:

include: icon-components/component-optional-props
replacements:
  - search: hAlign
    replace: horizontalAlign
  - search: vAlign
    replace: verticalAlign
  - search: hFlip
    replace: horizontalFlip
  - search: vFlip
    replace: verticalFlip

See below for more information on each optional property.

In addition to the properties mentioned above, the icon component accepts any other properties and events. All other properties and events will be passed to generated SVG element, so you can do stuff like setting the inline style, add title, add [prop]onClick event and so on.

Icon

include: icon-components/components/intro-icon

Color

include: icon-components/components/intro-color
<Icon icon="mdi:home" style="color: red" />

For various ways to set color, see how to change icon color in Iconify for Vue.

Dimensions

include: icon-components/components/intro-size
<Icon icon="mdi:home" style="font-size: 24px;" />

For various ways to change icon dimensions, see how to change icon dimensions in Iconify for Vue.

Transformations

include: icon-components/components/intro-transform

For more details see how to transform icon in Iconify for Vue.

Load event

include icon-components/components/onload-event

Functions {#functions}

include: icon-components/components/functions-list/header

Check available icons {#getting-icons}

include: icon-components/components/functions-list/getting-icons

Adding icons {#adding-icons}

include: icon-components/components/functions-list/adding-icons

Custom loaders {#custom-loaders}

include: icon-components/components/functions-list/custom-loaders

Helper functions {#helper}

include: icon-components/components/functions-list/helpers

API functions {#api}

include: icon-components/components/functions-list/api

Internal API functions {#internal}

include: icon-components/components/functions-list/internal
Icon Components

inline

title: Vertical Alignment in Iconify for Vue

Vertical alignment

This tutorial is part of Iconify for Vue tutorial.

include icon-components/vertical-align-intro

Inline attribute

include icon-components/components/inline-basic

src: icon-components/common/inline.vue
demo: true
class: iconify-inline-block

include icon-components/vertical-align-footer

Icon Components

list-icons

title: 'Iconify for Vue Function: listIcons'

Iconify for Vue function: listIcons

This tutorial is part of Iconify for Vue functions tutorial.

include icon-components/functions/list-icons/intro

Usage

include icon-components/functions/list-icons/props

Examples

src: icon-components/common/list-icons.js
replacements:
  - search: react
    replace: vue

Another example:

src: icon-components/common/list-icons2.js
replacements:
  - search: react
    replace: vue
Icon Components

load-icon

title: 'Iconify for Vue Function: loadIcon'
types:
  IconifyIconName: './icon-name.md'
  FullIconifyIcon: '/docs/libraries/utils/full-iconify-icon.md'
functions:
  loadIcons: './load-icons.md'

Iconify for Vue function: loadIcon

This tutorial is part of Iconify for Vue functions tutorial.

include icon-components/functions/load-icon/intro

Usage

include icon-components/functions/load-icon/props

IconifyIconName type

include types/iconify-icon-name

Examples

Using [type]Promise syntax:

src: icon-components/common/load-icon.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/vue'

Async/await syntax:

src: icon-components/common/load-icon-async.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/vue'

If you want to load multiple icons, see [func]loadIcons().

Icon Components

load-icons

title: 'Iconify for Vue Function: loadIcons'
types:
  IconifyIconName: './icon-name.md'
functions:
  getIcon: './get-icon.md'
  loadIcon: './load-icon.md'

Iconify for Vue function: loadIcons

This tutorial is part of Iconify for Vue functions tutorial.

include icon-components/functions/load-icons/intro

Usage

include icon-components/functions/load-icons/props

Icons list

include icon-components/functions/load-icons/props-icons

Callback

include icon-components/functions/load-icons/props-callback

IconifyIconName type

include types/iconify-icon-name

Examples

Simple callback that loads one icon:

src: icon-components/common/load-icons.js
replacements:
  - search: react
    replace: vue

Async version of [func]loadIcons():

src: icon-components/common/load-icons-async.js
replacements:
  - search: react
    replace: vue

Component example

This example dynamically loads icon data and renders [html]<slot /> while icon is being loaded. It is redundant because Vue component already does that, but it is used to show how to use [func]getIcon() and [func]loadIcons().

import { Icon, getIcon, loadIcons } from '@iconify/vue';
import { h, defineComponent, ref } from 'vue';

export default defineComponent({
	components: {
		Icon,
	},
	props: ['icon'],
	setup() {
		// Variable to store function to cancel loading
		const loader = ref(null);

		// Icon data
		const data = ref(null);

		// Function to check icon data
		const check = (icon: string) => {
			const iconData = getIcon(icon);

			// Cancel old loder
			if (loader.value) {
				loader.value();
				loader.value = null;
			}

			if (iconData) {
				data.value = iconData;
			} else {
				loader.value = loadIcons([icon], () => {
					data.value = getIcon(icon);
				});
			}
		};
		return {
			loader,
			data,
			check,
		};
	},
	watch: {
		icon: {
			immediate: true,
			handler(value) {
				// Check new value
				this.check(value);
			},
		},
	},
	// Stop loading
	unmounted() {
		const loader = this.loader.value;
		if (loader) {
			loader();
		}
	},
	render() {
		const icon = this.data;
		if (icon) {
			return h(Icon, {
				icon,
			});
		}
		return this.$slots.default ? this.$slots.default() : null;
	},
});

If you want to load only one icon, there is also [func]loadIcon() that is easier to use.

Icon Components

replace-ids

title: 'Iconify for Vue Function: replaceIDs'
functions:
  getIcon: './get-icon.md'

Iconify for Vue function: replaceIDs

This tutorial is part of Iconify for Vue functions tutorial.

include icon-components/functions/replace-ids/intro-component

Usage

include icon-components/functions/replace-ids/props

Example

include icon-components/functions/replace-ids/example-component

src: icon-components/common/replace-ids.js
replacements:
  - search: react
    replace: vue
Icon Components

set-fetch

title: 'Iconify for Vue Function: setFetch'

Iconify for Vue function: setFetch

This tutorial is part of Iconify for Vue functions tutorial.

include icon-components/functions/set-fetch/intro-component

Why is it needed? {#why}

include: icon-components/functions/set-fetch/why
include: icon-components/functions/set-fetch/nodejs

Usage

include: icon-components/functions/set-fetch/usage

Steps

include: icon-components/functions/set-fetch/component
replacements:
  - search: '@iconify/svelte'
    replace: '@iconify/vue'
include: icon-components/functions/set-fetch/bundle
Icon Components

transform

title: Transforming Icon in Iconify for Vue

Transformations

This tutorial is part of Iconify for Vue tutorial.

include icon-components/transform-intro

CSS vs Iconify transformations {#css}

include icon-components/transform-compare

Example:

src: icon-components/common/rotate-comparison.vue
demo: true
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

include icon-components/transform-compare-footer

Flip

include: icon-components/components/transform-flip
replacements:
  - search: hFlip
    replace: horizontalFlip
  - search: vFlip
    replace: verticalFlip
src: icon-components/common/flip.vue
hint: Using "flip" attribute
demo: true
extra:
  - src: icon-components/common/flip-alt.vue
    hint: Using "horizontalFlip" and "verticalFlip" attributes

Rotation

include icon-components/components/transform-rotate

src: icon-components/common/rotate.vue
demo: true

Rotate and flip

include icon-components/components/transform-footer

Property names

In other components, properties for flip are [attr]hFlip and [attr]vFlip. Vue has special treatment for properties that start with [attr]v-, so [attr]vFlip (same applies to [attr]vAlign attribute) attribute is not available without using tricky syntax.

Because of that, Vue component uses longer property names: [attr]verticalFlip instead of [attr]vFlip and [attr]horizontalFlip instead of [attr]hFlip for consistency.

Icon Components

add-api-provider

title: 'Iconify for Vue 2 Function: addAPIProvider'

Iconify for Vue 2 function: addAPIProvider

This tutorial is part of Iconify for Vue 2 functions tutorial.

include icon-components/functions/add-api-provider/intro

API providers

include icon-components/api-providers

Usage

include icon-components/functions/add-api-provider/props

Example

src: icon-components/common/add-api-provider.vue
replacements:
  - search: iconify/vue
    replace: iconify/vue2

include icon-components/functions/add-api-provider/footer

Icon Components

add-collection

title: 'Iconify for Vue 2 Function: addCollection'
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
functions:
  addIcon: './add-icon.md'

Iconify for Vue 2 function: addCollection

This tutorial is part of Iconify for Vue 2 functions tutorial.

include icon-components/functions/add-collection/intro

Usage

include icon-components/functions/add-collection/props

Examples

src: icon-components/common/add-collection.js
replacements:
  - search: react
    replace: vue2
src: icon-components/common/add-collection2.js
replacements:
  - search: react
    replace: vue2

include icon-components/functions/add-collection/notes

API provider

include icon-components/functions/add-collection/provider

Example:

src: icon-components/common/add-collection3.js
replacements:
  - search: react
    replace: vue2

Code above adds only one icon:

In component template this icon can be used like this:

<Icon icon="@custom:md:test" />

include icon-components/functions/add-collection/custom

One icon

include icon-components/functions/add-collection/footer

Icon Components

add-icon

title: 'Iconify for Vue 2 Function: addIcon'
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
functions:
  addCollection: './add-collection.md'

Iconify for Vue 2 function: addIcon

This tutorial is part of Iconify for Vue 2 functions tutorial.

include icon-components/functions/add-icon/intro

Usage

include icon-components/functions/add-icon/props

Examples

src: icon-components/common/add-icon.js
replacements:
  - search: react
    replace: vue2

include icon-components/functions/add-icon/notes

API provider

include icon-components/functions/add-icon/provider

Example:

src: icon-components/common/add-icon2.js
replacements:
  - search: react
    replace: vue2

Code above adds the following icon:

In component template this icon can be used like this:

<Icon icon="@custom:md:test" />

include icon-components/functions/add-icon/custom

One icon

include icon-components/functions/add-icon/footer

Icon Components

build-icon

title: "Iconify for Vue 2 Function: renderSVG"
types:
  IconifyIcon: "/docs/types/iconify-icon.md"
functions:
  replaceIDs: "./replace-ids.md"
  getIcon: "./get-icon.md"
  loadIcon: "./load-icon.md"
  iconExists: "./icon-exists.md"
  iconLoaded: "./icon-exists.md"

Iconify for Vue 2 function: buildIcon

This tutorial is part of Iconify for Vue 2 functions tutorial.

include icon-components/functions/build-icon/intro-component

Usage

include icon-components/functions/build-icon/usage

Result

include icon-components/functions/build-icon/result

Customizations

Second parameter is optional icon customizations. Available customizations:

include icon-components/customisations

For more details about dimensions see icon dimensions documentation.

For more details about transformations see icon transformations documentation.

Example

src: icon-components/common/build-icon.js
replacements:
  - search: "@iconify/svelte"
    replace: "@iconify/vue2"
extra:
  - src: icon-components/common/build-icon.json
    title: "Result:"
Icon Components

color

title: Changing Icon Color in Iconify for Vue 2

Icon color

This tutorial is part of Iconify for Vue 2 tutorial.

include: icon-components/components/color-intro
src: icon-components/common/color.vue
css: components/color.scss
demo: icon-components/common/color.html
class: components-color
replacements:
  - search: iconify/vue
    replace: iconify/vue2
include: icon-components/components/color-intro2

RGBA and HSLA colors {#opacity}

include icon-components/color-rgba

fill and stroke

include icon-components/color-fill

Icon Components

dimensions

title: Changing Icon Dimensions in Iconify for Vue 2

Icon dimensions

This tutorial is part of Iconify for Vue 2 tutorial.

include: icon-components/components/size-intro
src: icon-components/common/size.vue
css: components/size.scss
demo: icon-components/common/size.html
class: components-size
replacements:
  - search: iconify/vue
    replace: iconify/vue2

If you want to control icon size with [prop]width and [prop]height in CSS, see how to remove icon dimensions section below.

Units

include: icon-components/components/size-units
<Icon icon="mdi:home" :height="24" />
<Icon icon="mdi:home" height="24" />
<Icon icon="mdi:home" height="24px" />

Keyword "auto" {#auto}

include: icon-components/components/size-auto
<Icon icon="mdi:home" height="auto" />

Keywords "none" and "unset" {#unset}

include: icon-components/components/size-unset
src: icon-components/common/size-unset.vue
demo: true
class: 'icon-size icon-size--unset'
replacements:
  - search: iconify/vue
    replace: iconify/vue2
include: icon-components/components/size-unset-footer

Setting only width or height

In an example above, all icons only use [prop]height.

include icon-components/size-one

Example

include icon-components/size-example

Alignment

include icon-components/align-header

src: icon-components/common/alignment.vue
demo: icon-components/common/alignment.html
demoHint: Using box-shadow to show icon dimensions
class: highlight-box
replacements:
  - search: iconify/vue
    replace: iconify/vue2

include icon-components/align-behavior

Icon Components

disable-cache

title: 'Iconify for Vue 2 Function: disableCache'
functions:
  enableCache: './enable-cache.md'
  addIcon: './add-icon.md'
  addCollection: './add-collection.md'

Iconify for Vue 2 function: disableCache

This tutorial is part of Iconify for Vue 2 functions tutorial.

include icon-components/functions/cache/intro-disable

Usage

include icon-components/functions/cache/props

Storage types

include icon-components/functions/cache/storage-types

Examples

src: icon-components/common/disable-cache.js
replacements:
  - search: react
    replace: vue2

Another example:

src: icon-components/common/disable-cache2.js
replacements:
  - search: react
    replace: vue2

Notes

include icon-components/functions/cache/notes

Icon Components

enable-cache

title: 'Iconify for Vue 2 Function: enableCache'
functions:
  disableCache: './disable-cache.md'
  addIcon: './add-icon.md'
  addCollection: './add-collection.md'

Iconify for Vue 2 function: enableCache

This tutorial is part of Iconify for Vue 2 functions tutorial.

include icon-components/functions/cache/intro-enable

Usage

include icon-components/functions/cache/props

Storage types

include icon-components/functions/cache/storage-types

Example

src: icon-components/common/enable-cache.js
replacements:
  - search: react
    replace: vue2

Notes

include icon-components/functions/cache/notes

Icon Components

get-icon

title: 'Iconify for Vue 2 Function: getIcon'
types:
  IconifyIcon: '/docs/types/iconify-icon.md'

Iconify for Vue 2 function: getIcon

This tutorial is part of Iconify for Vue 2 functions tutorial.

include icon-components/functions/get-icon/intro

Usage

include icon-components/functions/get-icon/props

Examples

src: icon-components/common/get-icon.js
extra:
  - src: icon-components/iconify/get-icon.json
    title: 'Result:'
replacements:
  - search: react
    replace: vue2

Another example:

src: icon-components/common/get-icon2.js
extra:
  - src: icon-components/iconify/get-icon2.json
    title: 'Result:'
replacements:
  - search: react
    replace: vue2

Example with bad icon name, returns null:

src: icon-components/common/get-icon-null.js
replacements:
  - search: react
    replace: vue2
Icon Components

icon-exists

title: 'Iconify for Vue 2 Function: iconExists'

Iconify for Vue 2 function: iconExists

This tutorial is part of Iconify for Vue 2 functions tutorial.

include icon-components/functions/icon-exists/intro

Usage

include icon-components/functions/icon-exists/props

Example

import { iconExists } from '@iconify/vue2';

const icon = 'bi:arrow-left';
console.log(`Is ${icon} available?`, iconExists(icon) ? 'yes' : 'no');
Icon Components

icon-name

title: 'Iconify Type: IconifyIconName'

IconifyIconName type

include types/iconify-icon-name

API providers

include icon-components/api-providers-short

Examples

src: icon-components/iconify/icon-name.json
title: 'md:home'
hint: Because prefix does not contain hyphen, icon can also be referred as 'md-home'

Another example:

src: icon-components/iconify/icon-name2.json
title: '@local:line-icons:arrow-left'
Icon Components

index

title: Iconify for Vue 2
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "80+"
    value: "${counters.sets}+"
  - code: "@iconify/vue2@1"
    value: "${vue.import-vue2}"
types:
  IconifyIcon: "/docs/types/iconify-icon.md"
functions:
  addCollection: "./add-collection.md"
  addIcon: "./add-icon.md"
  iconExists: "./icon-exists.md"
  iconLoaded: "./icon-exists.md"
  listIcons: "./list-icons.md"
  loadIcons: "./load-icons.md"
  loadIcon: "./load-icon.md"
  getIcon: "./get-icon.md"
  enableCache: "./enable-cache.md"
  disableCache: "./disable-cache.md"
  addAPIProvider: "./add-api-provider.md"
  replaceIDs: "./replace-ids.md"
  buildIcon: "./build-icon.md"
  setFetch: "./set-fetch.md"

Iconify for Vue 2

include: icon-components/components/intro
replacements:
  - search: React
    replace: Vue

include notices/vue2

Installation

If you are using NPM:

npm install --save-dev @iconify/vue2@1

If you are using Yarn:

yarn add --dev @iconify/vue2@1

Usage

Install [npm]@iconify/vue2@1 and import component from it (component is exported as named export):

import { Icon } from "@iconify/vue2";

Then in template use [var]Icon component with icon name as [prop]icon parameter:

<Icon icon="mdi-light:home" />

Nuxt.js {#ssr}

Component is compatible with Nuxt.js.

The component does not retrieve icon data until it is mounted. For server side rendering it means generated HTML will not include SVGs, icons will be rendered only on the client side after hydration is complete.

If you do want to render SVGs on the server side, provide icon data as a parameter instead of icon name or use a different icon component.

Properties

You can pass any custom properties to component.

Required properties:

include: icon-components/component-optional-props
replacements:
  - search: hAlign
    replace: horizontalAlign
  - search: vAlign
    replace: verticalAlign
  - search: hFlip
    replace: horizontalFlip
  - search: vFlip
    replace: verticalFlip

See below for more information on each optional property.

In addition to the properties mentioned above, the icon component accepts any other properties and events. All other properties and events will be passed to generated SVG element, so you can do stuff like setting the inline style, add title, add [prop]onClick event and so on.

Icon

include: icon-components/components/intro-icon

Color

include: icon-components/components/intro-color
<Icon icon="mdi:home" style="color: red" />

For various ways to set color, see how to change icon color in Iconify for Vue.

Dimensions

include: icon-components/components/intro-size
<Icon icon="mdi:home" style="font-size: 24px;" />

For various ways to change icon dimensions, see how to change icon dimensions in Iconify for Vue.

Transformations

include: icon-components/components/intro-transform

For more details see how to transform icon in Iconify for Vue.

onLoad

include icon-components/components/onload

Functions {#functions}

include: icon-components/components/functions-list/header

Check available icons {#getting-icons}

include: icon-components/components/functions-list/getting-icons

Adding icons {#adding-icons}

include: icon-components/components/functions-list/adding-icons

Helper functions {#helper}

include: icon-components/components/functions-list/helpers

API functions {#api}

include: icon-components/components/functions-list/api

Internal API functions {#internal}

include: icon-components/components/functions-list/internal
Icon Components

inline

title: Vertical Alignment in Iconify for Vue 2

Vertical alignment

This tutorial is part of Iconify for Vue 2 tutorial.

include icon-components/vertical-align-intro

Inline attribute

include icon-components/components/inline-basic

src: icon-components/common/inline.vue
demo: true
class: iconify-inline-block
replacements:
  - search: iconify/vue
    replace: iconify/vue2

include icon-components/vertical-align-footer

Icon Components

list-icons

title: 'Iconify for Vue 2 Function: listIcons'

Iconify for Vue 2 function: listIcons

This tutorial is part of Iconify for Vue 2 functions tutorial.

include icon-components/functions/list-icons/intro

Usage

include icon-components/functions/list-icons/props

Examples

src: icon-components/common/list-icons.js
replacements:
  - search: react
    replace: vue2

Another example:

src: icon-components/common/list-icons2.js
replacements:
  - search: react
    replace: vue2
Icon Components

load-icon

title: 'Iconify for Vue 2 Function: loadIcon'
types:
  IconifyIconName: './icon-name.md'
  FullIconifyIcon: '/docs/libraries/utils/full-iconify-icon.md'
functions:
  loadIcons: './load-icons.md'

Iconify for Vue 2 function: loadIcon

This tutorial is part of Iconify for Vue 2 functions tutorial.

include icon-components/functions/load-icon/intro

Usage

include icon-components/functions/load-icon/props

IconifyIconName type

include types/iconify-icon-name

Examples

Using [type]Promise syntax:

src: icon-components/common/load-icon.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/vue2'

Async/await syntax:

src: icon-components/common/load-icon-async.js
replacements:
  - search: '@iconify/react'
    replace: '@iconify/vue2'

If you want to load multiple icons, see [func]loadIcons().

Icon Components

load-icons

title: 'Iconify for Vue 2 Function: loadIcons'
functions:
  getIcon: './get-icon.md'
  loadIcon: './load-icon.md'
types:
  IconifyIconName: './icon-name.md'

Iconify for Vue 2 function: loadIcons

This tutorial is part of Iconify for Vue 2 functions tutorial.

include icon-components/functions/load-icons/intro

Usage

include icon-components/functions/load-icons/props

Icons list

include icon-components/functions/load-icons/props-icons

Callback

include icon-components/functions/load-icons/props-callback

IconifyIconName type

include types/iconify-icon-name

Examples

Simple callback that loads one icon:

src: icon-components/common/load-icons.js
replacements:
  - search: react
    replace: vue2

Async version of [func]loadIcons():

src: icon-components/common/load-icons-async.js
replacements:
  - search: react
    replace: vue2

If you want to load only one icon, there is also [func]loadIcon() that is easier to use.

Icon Components

replace-ids

title: 'Iconify for Vue 2 Function: replaceIDs'
functions:
  getIcon: './get-icon.md'

Iconify for Vue 2 function: replaceIDs

This tutorial is part of Iconify for Vue 2 functions tutorial.

include icon-components/functions/replace-ids/intro-component

Usage

include icon-components/functions/replace-ids/props

Example

include icon-components/functions/replace-ids/example-component

src: icon-components/common/replace-ids.js
replacements:
  - search: react
    replace: vue2
Icon Components

set-fetch

title: 'Iconify for Vue 2 Function: setFetch'

Iconify for Vue function: setFetch

This tutorial is part of Iconify for Vue 2 functions tutorial.

include icon-components/functions/set-fetch/intro-component

Why is it needed? {#why}

include: icon-components/functions/set-fetch/why
include: icon-components/functions/set-fetch/nodejs

Usage

include: icon-components/functions/set-fetch/usage

Steps

include: icon-components/functions/set-fetch/component
replacements:
  - search: '@iconify/svelte'
    replace: '@iconify/vue2'
include: icon-components/functions/set-fetch/bundle
Icon Components

transform

title: Transforming Icon in Iconify for Vue 2

Transformations

This tutorial is part of Iconify for Vue 2 tutorial.

include icon-components/transform-intro

CSS vs Iconify transformations {#css}

include icon-components/transform-compare

Example:

src: icon-components/common/rotate-comparison.vue
demo: icon-components/common/rotate-comparison.html
demoHint: Using box-shadow to show icon dimensions
class: highlight-box
replacements:
  - search: iconify/vue
    replace: iconify/vue2

include icon-components/transform-compare-footer

Flip

include: icon-components/components/transform-flip
replacements:
  - search: hFlip
    replace: horizontalFlip
  - search: vFlip
    replace: verticalFlip
src: icon-components/common/flip.vue
hint: Using "flip" attribute
demo: icon-components/common/flip.html
extra:
  - src: icon-components/common/flip-alt.vue
    hint: Using "horizontalFlip" and "verticalFlip" attributes
replacements:
  - search: iconify/vue
    replace: iconify/vue2

Rotation

include icon-components/components/transform-rotate

src: icon-components/common/rotate.vue
demo: icon-components/common/rotate.html
replacements:
  - search: iconify/vue
    replace: iconify/vue2

Rotate and flip

include icon-components/components/transform-footer

Property names

In other components, properties for flip are [attr]hFlip and [attr]vFlip. Vue has special treatment for properties that start with [attr]v-, so [attr]vFlip (same applies to [attr]vAlign attribute) attribute is not available without using tricky syntax.

Because of that, Vue component uses longer property names: [attr]verticalFlip instead of [attr]vFlip and [attr]horizontalFlip instead of [attr]hFlip for consistency.

Iconify Icon

Iconify Icon

add-api-provider

title: 'Iconify Icon Web Component Function: addAPIProvider'

Web component function: addAPIProvider

This tutorial is part of Iconify Icon web component tutorial.

include icon-components/functions/add-api-provider/intro

API providers

include icon-components/api-providers

Usage

include icon-components/functions/add-api-provider/props

Example

src: icon-components/icon/add-api-provider.ts

include icon-components/functions/add-api-provider/footer

Iconify Icon

add-collection

title: 'Iconify Icon Web Component Function: addCollection'
types:
  IconifyJSON: '../types/iconify-json.md'
  IconifyIcon: '../types/iconify-icon.md'
functions:
  addIcon: './add-icon.md'

Web component function: addCollection

This tutorial is part of Iconify Icon web component tutorial.

include icon-components/functions/add-collection/intro

Usage

include icon-components/functions/add-collection/props

Examples

src: icon-components/common/add-collection.js
replacements:
  - search: '@iconify/react'
    replace: 'iconify-icon'
src: icon-components/common/add-collection2.js
replacements:
  - search: '@iconify/react'
    replace: 'iconify-icon'

include icon-components/functions/add-collection/notes

API provider

include icon-components/functions/add-collection/provider

Example:

src: icon-components/common/add-collection3.js
replacements:
  - search: '@iconify/react'
    replace: 'iconify-icon'

Code above adds only one icon:

In HTML this icon can be used like this:

<iconify-icon icon="@custom:md:test"></iconify-icon>

include icon-components/functions/add-collection/custom

One icon

include icon-components/functions/add-collection/footer

Iconify Icon

add-icon

title: 'Iconify Icon Web Component Function: addIcon'
types:
  IconifyJSON: '../types/iconify-json.md'
  IconifyIcon: '../types/iconify-icon.md'
functions:
  addCollection: './add-collection.md'

Web component function: addIcon

This tutorial is part of Iconify Icon web component tutorial.

include icon-components/functions/add-icon/intro

Usage

include icon-components/functions/add-icon/props

Examples

src: icon-components/common/add-icon.js
replacements:
  - search: '@iconify/react'
    replace: 'iconify-icon'

include icon-components/functions/add-icon/notes

API provider

include icon-components/functions/add-icon/provider

Example:

src: icon-components/common/add-icon2.js
replacements:
  - search: '@iconify/react'
    replace: 'iconify-icon'

Code above adds the following icon:

In HTML this icon can be used like this:

<iconify-icon icon="@custom:md:test"></iconify-icon>

include icon-components/functions/add-icon/custom

One icon

include icon-components/functions/add-icon/footer

Iconify Icon

build-icon

title: "Iconify Icon Web Component Function: buildIcon"
types:
  IconifyIcon: "../types/iconify-icon.md"
functions:
  getIcon: "./get-icon.md"
  loadIcon: "./load-icon.md"
  iconExists: "./icon-exists.md"
  iconLoaded: "./icon-exists.md"

Web component function: buildIcon

This tutorial is part of Iconify Icon web component tutorial.

include icon-components/functions/build-icon/intro-component

Usage

include icon-components/functions/build-icon/usage

Result

include icon-components/functions/build-icon/result

Customizations

Second parameter is optional icon customizations. Available customizations:

include icon-components/customisations

For more details about dimensions see icon dimensions documentation.

For more details about transformations see icon transformations documentation.

Example

src: icon-components/common/build-icon.js
replacements:
  - search: "@iconify/svelte"
    replace: "iconify-icon"
extra:
  - src: icon-components/common/build-icon.json
    title: "Result:"
Iconify Icon

color

title: Changing Icon Color in Iconify Icon Web Component

Icon color

This tutorial is part of Iconify Icon web component tutorial.

include: icon-components/components/color-intro
src: icon-components/icon/color.html
css: components/color.scss
demo: true
class: components-color
include: icon-components/components/color-intro2

RGBA and HSLA colors {#opacity}

include icon-components/color-rgba

Iconify Icon

custom-loaders

title: "Iconify Icon Web Component Functions: setCustomIconLoader and setCustomIconsLoader"
types:
  IconifyJSON: "../types/iconify-json.md"
  IconifyIcon: "../types/iconify-icon.md"
functions:
  loadIcon: "./load-icon.md"

Custom icon loaders

This tutorial is part of Iconify Icon web component tutorial.

include icon-components/functions/set-loaders/intro

Usage

include icon-components/functions/set-loaders/props

Example

src: icon-components/common/set-loader.js
replacements:
  - search: "@iconify/react"
    replace: "iconify-icon"

Make sure loader is set before any icons are rendered, otherwise component might attempt to load icon from API and fail to render it.

Iconify Icon

dimensions

title: Changing Icon Dimensions in Iconify Icon Web Component

Icon dimensions

This tutorial is part of Iconify Icon web component tutorial.

include: icon-components/components/size-intro
src: icon-components/icon/size-icon.html
css: icon/size.scss
demo: true
class: icon-size

If you want to control icon size with [prop]width and [prop]height in CSS, see how to remove icon dimensions section below.

Units

Both [prop]width and [prop]height can be used as properties and attributes.

Examples of [num]24px icon:

<iconify-icon icon="mdi:home" height="24"></iconify-icon>
<iconify-icon icon="mdi:home" height="24px"></iconify-icon>
<iconify-icon
	icon="mdi:home"
	style="font-size: 16px;"
	height="1.5em"
></iconify-icon>

Keyword "auto" {#auto}

include: icon-components/components/size-auto
<iconify-icon icon="mdi:home" height="auto"></iconify-icon>

Keywords "none" and "unset" {#unset}

include: icon-components/components/size-unset
src: icon-components/icon/size-unset.html
demo: true
class: 'icon-size icon-size--unset'
include: icon-components/components/size-unset-footer

Setting only width or height

In an example above, all icons only use [prop]height.

include icon-components/size-one

Example

include icon-components/size-example

Alignment

include icon-components/align-header

src: icon-components/icon/alignment.html
demo: true
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

include icon-components/align-behavior

You can control alignment with [attr]preserveAspectRatio attribute. Default value is [str]xMidYMid slice.

Slice

Instead of adding space around icon to fit it in bounding box, browser can also cut parts of icon that do not fit.

To cut parts of icon, add [attr]preserveAspectRatio="xMidYMid slice" to icon:

src: icon-components/icon/alignment-slice.html
demo: true
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

Horizontal alignment {#horizontal}

When...

...you can align icon horizontally.

To align icon horizontally, change [str]xMid in [attr]preserveAspectRatio to [str]xMin or [str]xMax:

Examples of aligning wide icon:

src: icon-components/icon/alignment-horizontal.html
demo: true
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

Examples of aligning tall icon with slice enabled:

src: icon-components/icon/alignment-horizontal-slice.html
demo: true
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

Vertical alignment {#vertical}

When...

...you can align icon vertically.

To align icon vertically, change [str]YMid in [attr]preserveAspectRatio to [str]YMin or [str]YMax:

Examples of aligning tall icon:

src: icon-components/icon/alignment-vertical.html
demo: true
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

Examples of aligning wide icon with slice enabled:

src: icon-components/icon/alignment-vertical-slice.html
demo: true
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

Vertical and horizontal alignment {#full-alignment}

You can add both horizontal and vertical alignment to icon.

One of alignments will have no effect. For example, if icon is too tall, horizontal alignment is ignored because icon is already aligned to both left and right sides.

src: icon-components/icon/alignment-both.html
demo: true
demoHint: Using box-shadow to show icon dimensions
class: highlight-box
Iconify Icon

disable-cache

title: "Iconify Icon Web Component Function: disableCache"
functions:
  enableCache: "./enable-cache.md"
  addIcon: "./add-icon.md"
  addCollection: "./add-collection.md"

Web component function: disableCache

This tutorial is part of Iconify Icon web component tutorial.

include icon-components/functions/cache/deprecated

include icon-components/functions/cache/intro-disable

Usage

include icon-components/functions/cache/props

Storage types

include icon-components/functions/cache/storage-types

Examples

src: icon-components/common/disable-cache.js
replacements:
  - search: "@iconify/react"
    replace: "iconify-icon"

Another example:

src: icon-components/common/disable-cache2.js
replacements:
  - search: "@iconify/react"
    replace: "iconify-icon"

Notes

include icon-components/functions/cache/notes

Iconify Icon

enable-cache

title: "Iconify Icon Web Component Function: enableCache"
functions:
  disableCache: "./disable-cache.md"
  addIcon: "./add-icon.md"
  addCollection: "./add-collection.md"

Web component function: enableCache

This tutorial is part of Iconify Icon web component tutorial.

include icon-components/functions/cache/deprecated

include icon-components/functions/cache/intro-enable

Usage

include icon-components/functions/cache/props

Storage types

include icon-components/functions/cache/storage-types

Example

src: icon-components/common/enable-cache.js
replacements:
  - search: "@iconify/react"
    replace: "iconify-icon"

Notes

include icon-components/functions/cache/notes

Iconify Icon

get-icon

title: 'Iconify Icon Web Component Function: getIcon'
types:
  IconifyIcon: '/docs/types/iconify-icon.md'

Web component function: getIcon

This tutorial is part of Iconify Icon web component tutorial.

include icon-components/functions/get-icon/intro

Usage

include icon-components/functions/get-icon/props

Examples

src: icon-components/common/get-icon.js
extra:
  - src: icon-components/iconify/get-icon.json
    title: 'Result:'
replacements:
  - search: '@iconify/react'
    replace: 'iconify-icon'

Another example:

src: icon-components/common/get-icon2.js
extra:
  - src: icon-components/iconify/get-icon2.json
    title: 'Result:'
replacements:
  - search: '@iconify/react'
    replace: 'iconify-icon'

Example with bad icon name, returns null:

src: icon-components/common/get-icon-null.js
replacements:
  - search: '@iconify/react'
    replace: 'iconify-icon'
Iconify Icon

icon-exists

title: "Iconify Icon Web Component Function: iconLoaded"

Web component function: iconLoaded

This tutorial is part of Iconify Icon web component tutorial.

include icon-components/functions/icon-loaded/intro

Usage

include icon-components/functions/icon-loaded/props

Example

import { iconLoaded, loadIcons } from "iconify-icon";

function renderLeftArrow() {
  // Check if 'bi:arrow-left' is available
  if (iconLoaded("bi:arrow-left")) {
    // Return HTML for 'bi:arrow-left'
    return '<iconify-icon icon="bi:arrow-left"></iconify-icon>';
  }

  // Load icon. Bad example because this should use a callback to re-render arrow in a stateful
  // component, but this code example is about iconLoaded(), not loadIcons()

  // Function loadIcons() is asynchronous, so in this example it will only trigger loading, but
  // icon data will not be available immediately
  loadIcons(["bi:arrow-left"]);

  // Return '<'
  return "<span>&lt;</span>";
}

Legacy

include icon-components/functions/icon-loaded/legacy

Iconify Icon

icon-name

title: 'Iconify Type: IconifyIconName'

IconifyIconName type

include types/iconify-icon-name

API providers

include icon-components/api-providers-short

Examples

src: icon-components/iconify/icon-name.json
title: 'md:home'
hint: Because prefix does not contain hyphen, icon can also be referred as 'md-home'

Another example:

src: icon-components/iconify/icon-name2.json
title: '@local:line-icons:arrow-left'
Iconify Icon

icon

title: Icon Attribute in Iconify Icon Web Component
navigation: './index.md'
functions:
  addIcon: './add-icon.md'

Icon attribute

This tutorial is part of Iconify Icon web component tutorial.

When using Iconify icon components, you can pass icon data to component instead of icon name, like this:

import { Icon } from '@iconify/react';
import arrowLeft from '@iconify-icons/bi/arrow-left';

function renderLeftArrow() {
	return <Icon icon={arrowLeft} />;
}

Unfortunately, the same syntax is not available for the web component. Attributes in HTML elements cannot be complex objects, making it harder to pass icon data to a web component.

How to solve this?

Assigning icon name

Best and easiest solution is to assign icon name to icon using [func]addIcon() function:

import { addIcon } from 'iconify-icon';
import arrowLeft from '@iconify-icons/bi/arrow-left';

addIcon('arrow-left', arrowLeft);

function renderLeftArrow() {
	return '<iconify-icon icon="arrow-left"></iconify-icon>';
}

Serialising data

Web component also supports serialised objects for [prop]icon attribute:

import arrowLeft from '@iconify-icons/bi/arrow-left';

function renderLeftArrow() {
	const node = document.createElement('iconify-icon');
	node.setAttribute('icon', JSON.stringify(arrowLeft));
	return node.outerHTML;
}

Or this if you need to render HTML:

import arrowLeft from '@iconify-icons/bi/arrow-left';

const replacements = {
	'&': '&amp;',
	'<': '&lt;',
	'>': '&gt;',
	'"': '&quot;',
	"'": '&#039;',
};

function stringify(data) {
	return JSON.stringify(arrowLeft).replace(
		/[&<>"']/g,
		(char) => replacements[char]
	);
}

const arrowLeftString = JSON.stringify(arrowLeft);

function renderLeftArrow() {
	return '<iconify-icon icon="' + arrowLeftString + '"></iconify-icon>';
}

Using property

Instead of setting attribute, you can also set property, which accepts objects:

import arrowLeft from '@iconify-icons/bi/arrow-left';

function renderLeftArrow() {
	const node = document.createElement('iconify-icon');
	node.icon = arrowLeft;
	return node.outerHTML;
}
Iconify Icon

index

title: Iconify Icon Web Component
replacements:
  - code: "60k"
    value: "${counters.icons-short}"
  - code: "0.0.4"
    value: "${iconify-icon.version}"
types:
  IconifyIcon: "../types/iconify-icon.md"
functions:
  addCollection: "./add-collection.md"
  addIcon: "./add-icon.md"
  iconExists: "./icon-exists.md"
  iconLoaded: "./icon-exists.md"
  listIcons: "./list-icons.md"
  loadIcons: "./load-icons.md"
  loadIcon: "./load-icon.md"
  getIcon: "./get-icon.md"
  enableCache: "./enable-cache.md"
  disableCache: "./disable-cache.md"
  addAPIProvider: "./add-api-provider.md"
  buildIcon: "./build-icon.md"
  setFetch: "./set-fetch.md"
  setCustomIconLoader: "./custom-loaders.md"
  setCustomIconsLoader: "./custom-loaders.md"

Iconify Icon web component

Iconify Icon is a web component renders icons.

Usage

It is designed to be as easy to use as possible.

src: icon-components/icon/usage.html
demo: true
demoFirst: false
class: sample-big

Supported frameworks

Web component can be used in HTML without any UI framework. See usage examples below.

It also works great with all modern frameworks that support web components:

However, some UI frameworks require custom wrappers:

Layout shift

Web component is not rendered instantly. There could be a few milliseconds delay.

This is caused by:

This might cause layout shift.

To avoid layout shift, add this to your CSS:

iconify-icon {
  display: inline-block;
  width: 1em;
  height: 1em;
}

Icon data on demand

Instead of embedding an entire icon, all you need to do is provide an icon name in [prop]icon attribute.

Web component will retrieve icon data from Iconify API, then will render SVG in shadow DOM.

There are over 60k icons available from many open source icon sets.

Don't want to rely on third party API servers? You can host your own Iconify API. You can also use it with your own icons.

Shadow DOM

SVG is rendered in shadow DOM. What does that mean?

Sometimes this can be a disadvantage, for example, if you do want to access icon content to perform CSS or JavaScript based animations. If you do not want a web component that uses shadow DOM, take a look at Iconify icon components.

SSR hydration {#ssr}

One of the issues a web component solves is a hydration, which is used by many modern UI frameworks.

Server side rendering is becoming more and more popular, hydration is complex and can easily be broken by a mismatched DOM.

What is hydration? Hydration is a process of matching content generated on server and content generated by UI framework in browser. Instead of re-rendering document, a UI framework uses HTML generated on server. This is the basic explanation. It is actually more complex than that, see various articles on SSR hydration.

There are several issues with hydrating icons:

Shadow DOM used by web components solves hydration problems. When a UI framework renders icon on server, it only renders [tag]iconify-icon element. During hydration process, UI framework only checks [tag]iconify-icon element, but not actual icon. This means:

Using shadow DOM to render icon leads to better experience for developers. No need to configure anything, no need to worry about icon data, no need to worry about conflicts. It just works.

Rendering only visible icons

As of version 2.0.0 of the web component, icons are rendered only when visible to the visitor.

For long documents with many icons, this improves the performance of pages by a lot.

As of version 2.1.0, you can opt out of this behavior by adding [html]noobserver attribute to web component's HTML:

<iconify-icon icon="mdi:home" noobserver></iconify-icon>

Why not use icon font? {#icon-font}

Shadow DOM used by web component has big advantages over usual SVGs or framework specific components, but what about icon fonts?

Do not use icon fonts!!!

Icon fonts do not belong in modern web. They were a great solution when Internet Explorer was popular, web components did not exist and SVG support was buggy. Those bad times are over.

Registering the web component

For the web component to work, it needs to be registered. [npm]iconify-icon package does that automatically. All you need to do is include it on a page.

If you are building a project with a bundler, you can include the script by installing [npm]iconify-icon as a dependency and importing it in your project:

import "iconify-icon";

If you are not using bundles or want icon web component to be imported separately, add script to your document:

<script src="https://code.iconify.design/iconify-icon/0.0.4/iconify-icon.min.js"></script>

or

<script src="https://cdn.jsdelivr.net/npm/iconify-icon@0.0.4/dist/iconify-icon.min.js"></script>

Nuxt

When using component with Nuxt, you need to tell it that [tag]iconify-icon is a web component.

Example of [file]nuxt.config.ts:

import { defineNuxtConfig } from "nuxt3";

export default defineNuxtConfig({
  vue: {
    compilerOptions: {
      isCustomElement: (tag) => tag === "iconify-icon",
    },
  },
});

Attributes

There are several attributes to customise icon appearance.

To change color (color can be changed only for monotone icons) or size, use style:

src: icon-components/icon/color-size.html
demo: true
class: sample-big

You can also change size using [attr]width and/or [attr]height attributes:

src: icon-components/icon/size.html
demo: true

If only one size attribute is set, another attribute is calculated using icon's width/height ratio.

You can also transform icon. Unlike CSS transformations, these transformations are done inside icon, which also affects icon's [prop]viewBox:

src: icon-components/icon/transform.html
demo: true

Attributes list

All attributes are also available as properties, so you can access them easy in JavaScript when working with elements.

Required attribute:

Optional attributes:

Functions

For advanced developers, web component offers several functions to control it.

These functions can be used to load custom icons, get icon data, preload icons from API, configure custom API and so on. See functions list below.

Functions can be imported from:

First method is the most reliable because it is a simple import. It is used in all examples:

import { loadIcon } from "iconify-icon";

const name = "mdi:home";
loadIcon(name)
  .then((data) => {
    console.log("Loaded data for", name);
  })
  .catch(console.error);

For second method, class can be retrieved from custom elements' registry:

const IconifyIcon = window.customElements.get("iconify-icon");

const name = "mdi:home";
IconifyIcon.loadIcon(name)
  .then((data) => {
    console.log("Loaded data for", name);
  })
  .catch(console.error);

Third method can be used after creating a new icon element or accessing an existing element:

const IconifyIcon = document.createElement("iconify-icon");

const name = "mdi:home";
IconifyIcon.loadIcon(name)
  .then((data) => {
    console.log("Loaded data for", name);
  })
  .catch(console.error);

Functions are split in several groups (click function name to see more details and examples):

Instance functions {#instance}

These functions are available only on web component nodes:

Check available icons {#getting-icons}

include: icon-components/components/functions-list/getting-icons

Adding icons {#adding-icons}

include: icon-components/components/functions-list/adding-icons

Custom loaders {#custom-loaders}

include: icon-components/components/functions-list/custom-loaders

Helper functions {#helper}

API functions {#api}

include: icon-components/components/functions-list/api

Internal API functions {#internal}

include: icon-components/components/functions-list/internal
Iconify Icon

inline

title: Vertical Alignment in Iconify Icon Web Component

Vertical alignment

This tutorial is part of Iconify Icon web component tutorial.

include icon-components/vertical-align-intro

Inline attribute

include icon-components/components/inline-basic

src: icon-components/icon/inline.html
demo: true
class: iconify-inline-block

include icon-components/vertical-align-footer

Iconify Icon

list-icons

title: 'Iconify Icon Web Component Function: listIcons'

Web component function: listIcons

This tutorial is part of Iconify Icon web component tutorial.

include icon-components/functions/list-icons/intro

Usage

include icon-components/functions/list-icons/props

Examples

src: icon-components/common/list-icons.js
replacements:
  - search: '@iconify/react'
    replace: 'iconify-icon'

Another example:

src: icon-components/common/list-icons2.js
replacements:
  - search: '@iconify/react'
    replace: 'iconify-icon'
Iconify Icon

load-icon

title: 'Iconify Icon Web Component Function: loadIcon'
types:
  IconifyIconName: './icon-name.md'
  FullIconifyIcon: '/docs/libraries/utils/full-iconify-icon.md'
functions:
  loadIcons: './load-icons.md'

Web component function: loadIcon

This tutorial is part of Iconify Icon web component tutorial.

include icon-components/functions/load-icon/intro

Usage

include icon-components/functions/load-icon/props

IconifyIconName type

include types/iconify-icon-name

Examples

Using [type]Promise syntax:

src: icon-components/common/load-icon.js
replacements:
  - search: '@iconify/react'
    replace: 'iconify-icon'

Async/await syntax:

src: icon-components/common/load-icon-async.js
replacements:
  - search: '@iconify/react'
    replace: 'iconify-icon'

If you want to load multiple icons, see [func]loadIcons().

Iconify Icon

load-icons

title: 'Iconify Icon Web Component Function: loadIcons'
functions:
  getIcon: './get-icon.md'
  loadIcon: './load-icon.md'
types:
  IconifyIconName: './icon-name.md'

Web component function: loadIcons

This tutorial is part of Iconify Icon web component tutorial.

include icon-components/functions/load-icons/intro

Usage

include icon-components/functions/load-icons/props

Icons list

include icon-components/functions/load-icons/props-icons

Callback

include icon-components/functions/load-icons/props-callback

IconifyIconName type

include types/iconify-icon-name

Examples

Simple callback that loads one icon:

src: icon-components/common/load-icons.js
replacements:
  - search: '@iconify/react'
    replace: 'iconify-icon'

Async version of [func]loadIcons():

src: icon-components/common/load-icons-async.js
replacements:
  - search: '@iconify/react'
    replace: 'iconify-icon'

If you want to load only one icon, there is also [func]loadIcon() that is easier to use.

Iconify Icon

modes

title: Rendering Modes in Iconify Icon Web Component

Rendering modes

This tutorial is part of Iconify Icon web component tutorial.

Web component supports several icon rendering modes.

Modes

There are 4 modes supported by web component:

Demo showing 2 icons (one monotone, one with palette) rendered with 4 modes:

include icon-components/modes-demo

Code samples

What do these modes actually look like in DOM?

Examples for [icon]mdi:home (used in modes demo above) icon:

hint: 'svg mode'
src: icon-components/common/modes-svg.html
extra:
  - src: icon-components/common/modes-bg.html
    hint: 'bg mode'
  - src: icon-components/common/modes-mask.html
    hint: 'mask mode'

Why not just render SVG? {#why}

You are probably wondering, why is it even needed? Isn't [tag]svg enough?

Rendering icon as [tag]svg works for most icons, but it does not always work for icons that use SVG animations.

SVG animations cannot start until document is ready. It might seem like a small thing, but animations not rendering quickly enough can cause bad user experience. This issue can be caused by small things, such as statistics script failing to load or ad code loading slowly. If at least one server that page is loading resources from is unreachable, it might break all animated SVGs on page. Async and defer attributes do not help. Issue can even be caused by script in an iframe.

Animation delay demo {#delay-demo}

Below is an [tag]iframe that shows icon rendering issue. It contains animated icon, rendered as [tag]svg and as background image. Both icons render instantly, but animation in [tag]svg does not start for few seconds because document is still loading.

include icon-components/frames/delay-demo-1up

To make things worse, this demo, which is in [tag]iframe, affects the main document. Logo on this page is rendered as [tag]svg and it contains animations. Refresh this page to see how slow script in a frame prevents SVG animations in unrelated icons in the main document.

Backgrounds and masks

Background images cannot use [prop]currentColor, but they do keep icon's palette, so icons with palette can be rendered as background image.

But what to do if icon uses [prop]currentColor? Solution is to use icon as mask and set background color to [prop]currentColor.

Combination of background and mask images make it possible to use almost all SVGs as URLs. The only icons that cannot be rendered correctly are icons that mix [prop]currentColor and hardcoded palette.

See Icons in Pure CSS article by Anthony Fu that explains it in more details.

SVG animations

When icon has animations, animations start immediately if it is rendered as mask or background, solving animation delay issue mentioned few sections above.

However, there is another issue: browser cache in Chrome. Image is rendered as URL. If URL is already in browser cache, Chrome does not restart animation. That means consequent renders of the same animated icons can bug out.

include icon-components/frames/delay-demo-freeze-1up

So there are issues with SVG animations when used as background or mask too. Web component solves it by adding random commented out content to icon, which causes it to bypass browser cache.

include icon-components/frames/delay-demo-icon-1up

Which mode to use? {#choices}

Web component will automatically use the best mode:

Iconify Icon

react

title: 'Iconify Icon Web Component with React'

Iconify Icon web component with React

This tutorial is part of Iconify Icon web component tutorial.

Iconify icon web component works well with React, but there are few problems:

Iconify Icon for React

These problems are solved by Iconify Icon for React.

It is a wrapper for web component that provides support for [prop]className, allows to use objects with [prop]icon and provides typings for React component.

Installation

Instead of [npm]iconify-icon package, install [npm]@iconify-icon/react package:

npm install --save-dev @iconify-icon/react
yarn add --dev @iconify-icon/react

Usage

Import [prop]Icon component from [npm]@iconify-icon/react, set icon in [prop]icon property:

import React from 'react';
import { Icon } from '@iconify-icon/react';

export function Alert() {
	return (
		<div className="alert">
			<Icon icon="mdi-light:alert" />
			Important notice with alert icon!
		</div>
	);
}

Usage with objects

You can pass objects in [prop]icon property:

import React from 'react';
import { Icon } from '@iconify-icon/react';
import alertIcon from '@iconify-icons/mdi-light/alert';

export function Alert() {
	return (
		<div className="alert">
			<Icon icon={alertIcon} />
			Important notice with alert icon!
		</div>
	);
}

Functions

All other functions, listed in Iconify Icon web component tutorial, are available. You can import them directly from [npm]@iconify-icon/react package:

import React from 'react';
import { Icon, addIcon } from '@iconify-icon/react';

addIcon('alert', {
	body: '<path fill="currentColor" d="M1 21L11.5 2.813L22 21H1Zm19.268-1L11.5 4.813L2.732 20h17.536ZM11 14v-4h1v4h-1Zm0 2h1v2h-1v-2Z"/>',
	width: 24,
	height: 24,
});

export function Alert() {
	return (
		<div className="alert">
			<Icon icon="alert" />
			Important notice with alert icon!
		</div>
	);
}

See Iconify Icon web component for list of all attributes, functions and usage examples. [npm]@iconify-icon/react is only a wrapper for [npm]iconify-icon, not a different component, it supports all the same properties and functions.

Iconify Icon

set-fetch

title: 'Iconify Icon Web Component Function: setFetch'

Web component function: setFetch

This tutorial is part of Iconify Icon web component tutorial.

include icon-components/functions/set-fetch/intro-component

Why is it needed? {#why}

include: icon-components/functions/set-fetch/why
include: icon-components/functions/set-fetch/nodejs

Usage

include: icon-components/functions/set-fetch/usage

Steps

include: icon-components/functions/set-fetch/component
replacements:
  - search: '@iconify/svelte'
    replace: 'iconify-icon'
include: icon-components/functions/set-fetch/bundle
Iconify Icon

solid

title: 'Iconify Icon Web Component with SolidJS'

Iconify Icon web component with SolidJS

This tutorial is part of Iconify Icon web component tutorial.

Currently, SolidJS has poor support for web components. It is caused by issues in the web components spec. When setting a property to a web component, it sometimes does not work as expected.

Workaround

Workaround for Solid usage is to force Solid to use attributes instead of properties:

<iconify-icon attr:icon="mdi-light:home"></iconify-icon>

Iconify Icon for Solid

Iconify Icon for Solid solves that by mapping properties to attributes in a native Solid component, so you can use the web component without any issues.

It also provides typings for the component, making it easier to use in JSX and supports objects for [prop]icon property.

Installation

Instead of [npm]iconify-icon package, install [npm]@iconify-icon/solid package:

npm install --save-dev @iconify-icon/solid
yarn add --dev @iconify-icon/solid

Usage

Import [prop]Icon component from [npm]@iconify-icon/solid, set icon in [prop]icon property:

import { Icon } from '@iconify-icon/solid';

export default () => {
	return (
		<div class="alert">
			<Icon icon="mdi-light:alert" />
			Important notice with alert icon!
		</div>
	);
};

Usage with objects

You can pass objects in [prop]icon property:

import { Icon } from '@iconify-icon/solid';
import alertIcon from '@iconify-icons/mdi-light/alert';

export default () => {
	return (
		<div class="alert">
			<Icon icon={alertIcon} />
			Important notice with alert icon!
		</div>
	);
};

Functions

All other functions, listed in Iconify Icon web component tutorial, are available. You can import them directly from [npm]@iconify-icon/solid package:

import { Icon, addIcon } from '@iconify-icon/solid';

addIcon('alert', {
	body: '<path fill="currentColor" d="M1 21L11.5 2.813L22 21H1Zm19.268-1L11.5 4.813L2.732 20h17.536ZM11 14v-4h1v4h-1Zm0 2h1v2h-1v-2Z"/>',
	width: 24,
	height: 24,
});

export default () => {
	return (
		<div class="alert">
			<Icon icon="alert" />
			Important notice with alert icon!
		</div>
	);
};

See Iconify Icon web component for the list of all attributes, all functions and usage examples. [npm]@iconify-icon/solid is only a wrapper for [npm]iconify-icon, not a different component, it supports all the same properties and functions.

Iconify Icon

transform

title: Transforming Icon in Iconify Icon Web Component

Transformations

This tutorial is part of Iconify Icon web component tutorial.

include icon-components/transform-intro

CSS vs Iconify transformations {#css}

include icon-components/transform-compare

Example:

src: icon-components/icon/rotate-comparison.html
demo: true
demoHint: Using box-shadow to show icon dimensions
class: highlight-box

include icon-components/transform-compare-footer

Flip

include icon-components/components/transform-flip

src: icon-components/icon/flip.html
hint: Using "flip" attribute
demo: true

Rotation

include icon-components/components/transform-rotate

src: icon-components/icon/rotate.html
demo: true

Rotate and flip

include icon-components/components/transform-footer

Icons

Icons

all

title: Iconify Icon Sets Package
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "60k"
    value: "${counters.icons-short}"
  - code: "80 icon sets"
    value: "${counters.sets} icon sets"
types:
  IconifyJSON: "/docs/types/iconify-json.md"
  IconifyInfo: "/docs/types/iconify-json-metadata.md"
  LegacyIconifyInfo: "/docs/types/iconify-json-metadata.md"
  IconifyChars: "/docs/types/iconify-json-metadata.md#chars"
  IconifyMetaData: "/docs/types/iconify-json-metadata.md#iconify-categories"
functions:
  exportJSONPackage: "/docs/libraries/tools/export/json-package.md"
  getIconData: "/docs/libraries/utils/get-icon-data.md"
  getIcons: "/docs/libraries/utils/get-icons.md"

Iconify icon sets package

You can get the latest version of open source icon data from the following sources:

You can also get smaller packages, but it is not covered in this document. See icon data documentation.

Contents

Package contains:

Icon sets list

Icon sets list is stored in [file]collections.json.

Contents are a simple object, where key is icon set prefix, value is icon set information in [type]IconifyInfo format. Information includes icon set name, author information, license, number of files and 3 sample files to display.

Additionally, [file]collections.md contains the same data, but in human-readable format.

Icon sets

Each icon has is stored in one file, located in directory [file]json/. File name matches icon set prefix, which you can find as key in icon sets list in [file]collections.json.

Contents are stored in [type]IconifyJSON format.

Icon set files contain all icon set data, including info and metadata. If you want to get minimal version without extra stuff, use small packages instead.

Maintenance

Package is automatically updated every few days, so it always includes the latest icons. If you want to use the latest icons, all you have to do is keep dependencies in your project up to date.

If you are using Iconify API, you do not need to do anything because changes are automatically pushed to API servers within minutes after being published.

Reading data {#tools}

For reading icon sets, you can use:

To use icon set packages with Iconify Utils, follow these steps:

Helper functions {#helpers}

Package contains simple helper functions for Node.js and PHP.

Node.js functions {#functions-node}

In Node.js version of [npm]@iconify/json functions are asynchronous:

All functions listed above are asynchronous and require using [func]await before function name (see example below).

There are also few synchronous functions:

PHP functions

PHP is a synchronous language, so functions for PHP are identical for versions 1 and 2.

Use [prop]Iconify\IconsJSON\Finder class that has the following static functions:

Example

Example:

src: icons/json/finder.js
title: Node.js
extra:
  - src: icons/json/finder.php
    title: PHP

These helper functions only list and locate icon sets.

For reading icon sets, you can use Iconify Utils.

Adding icon sets {#submit}

Do you know a good open source icon set that is missing in Iconify icon sets? Open an issue on GitHub to request to add it to Iconify icon sets.

Licences

All icon sets available in Iconify collections are released under free or open source licence, which allows redistribution. See each icon set's info for details.

Icons

collections

title: Icon Sets List
types:
  IconifyInfo: '/docs/types/iconify-json-metadata.md'

Available icon sets list

If you are not using full icon sets package, which contains [file]collections.json, you might need to know list of available open source icon sets.

There are several ways to get it:

In [npm]@iconify/collections and full icon sets package you'll find [file]collections.json with list of all icon sets.

Structure

Data is stored as an object, where key is icon set prefix, value is icon set information in [type]IconifyInfo format.

Import

If you are using [npm]@iconify/collections package, you can import icon sets list directly from [file]@iconify/collections/collections.json as default import or use named import:

import { collections } from '@iconify/collections';

Code above uses JSON modules, which does not work with outdated version of Node.js. If you are using older version of Node, importing JSON files requires running script with [str]--experimental-json-modules flag.

Alternatively, for older versions of Node.js you can use [func]require():

const collections = require('@iconify/collections/collections.json');
Icons

custom

title: Custom Icon Sets
types:
  IconifyJSON: '/docs/types/iconify-json.md'
functions:
  exportJSONPackage: '/docs/libraries/tools/export/json-package.md'

Custom icon sets

You can also use Iconify with custom icons.

Most icon components and plugins support custom icon sets. The only exception are plugins that are not meant to work with custom icon sets, such as Iconify plugin for Figma.

Format

How custom icon sets are handled depends on your use case.

All tools in Iconify ecosystem work with [type]IconifyJSON format.

Some icon components and plugins that are designed to work in Node.js (server side rendering or works with bundlers) can import individual SVG files, but usually they convert icons to [type]IconifyJSON format.

Import tools

Importing custom icon sets can be done at build time in Node.js environment.

It is done with Iconify Tools package.

Typical import process:

See Iconify Tools code examples for code samples.

Using custom icon sets

Usage depends on where you want to use it. See documentation of icon component you want to use icons with.

If icon component you want to use loads icon data on demand, you probably want to set up your own Iconify API to host custom icon sets.

Icons

icon-basics

title: "Getting Started: Icons Cleanup"
types:
  IconifyJSON: "/docs/types/iconify-json.md"
  IconifyIcon: "/docs/types/iconify-icon.md"
functions:
  getIconData: "/docs/libraries/utils/get-icon-data.md"
  parseIconSet: "/docs/libraries/utils/parse-icon-set.md"
  defaultIconProps: "/docs/libraries/utils/default-icon-props.md"

Icons Cleanup

One of goals of Iconify project is to make icons easy to use.

This is not as simple as running icons through popular optimisation tools. Icon parsing in Iconify is very strict and process is much more invasive.

Icons are modified, so they can be used the same way regardless of icon set.

What exactly is done? {#process}

Each icon is:

Naming convention

To make icons easy to use regardless of their source, all icons follow the same naming convention.

Allowed characters in icon names are [str]a-z, numbers and [str]-. Hyphen cannot be used at start or end of name, 2 hyphens in a row [str]-- are not allowed.

Examples of valid icon names: [str]home-outline, [str]1st-place-medal, [str]camera-with-flash.

Validation

When icons are imported and validated, icons that contain any of the following are not allowed:

Additionally, everything that does not affect icon rendering is removed. Many bad editors leave a lot of junk code in generated SVG, all of that is removed.

This is done during import process for open source icon sets using Iconify Tools. Custom icon sets might not follow the same guidelines.

Clean up and optimisation

Clean up and optimisation process removes all unnecessary code, making icon as small as possible, without breaking icon.

For more details about icon cleanup, see icons clean up process.

Palette

Palette is always checked and fixed if necessary.

What exactly is done depends on type of icon.

There are 2 types of icons:

What is the difference?

Hardcoded palette

Colors in icons with hardcoded palette cannot be changed.

Examples:

include: common/icon-types-palette

In CSS these icons are used as background images.

Palette in such icons is kept as is.

Monotone icons

All monotone icons are modified to use [prop]currentColor for color.

This makes it easy to change icon color by changing text color in CSS.

Examples:

include: common/icon-types-monotone

Hover samples above to see color change.

Why not [prop]fill? Main reason is because many icons use [prop]stroke for color. Using [prop]fill to set color is bad practice because it limits your icons to only icons that use [prop]fill. It also prevents icons from being used as mask images because background color cannot be set to fill color.

In CSS these icons are used as mask images, see using SVG in CSS for details.

Do not set fill! {#fill}

Some icon sets recommend changing color by changing [prop]fill, but you should never do that with Iconify!

This is a very bad practice because not all icons use fill. Many icons use [prop]stroke, but you cannot change [prop]stroke because it would add stroke to icons that do not have [prop]stroke.

To avoid all that mess, Iconify changes color in monotone icons to [prop]currentColor, so you can change icon color by changing text color, regardless of how icon is structured.

Mixing currentColor and custom colors

While it is possible to mix monotone and hardcoded palette, it is a very bad idea. Icon with mix of [prop]currentColor and hardcoded colors is unusable because:

Therefore, icons with mixed palette are not allowed in Iconify open source icon sets repository.

Format

Icons are stored converted to [type]IconifyIcon format, then stored in icon sets in [type]IconifyJSON format.

Data is stored in easy to use JSON files.

Custom type

Why is icon stored in custom [type]IconifyIcon type instead of SVG?

Format splits icon attributes for [tag]svg element and content. This it makes it easy to alter SVG without parsing XML: resize, change [prop]viewBox, render as components without parsing JSX, append/prepend shapes to icon, etc.

Icon sets

Multiple icons are stored in an icon set. See icon sets documentation for details.

Icons

icon-data

title: Open Source Icon Data
replacements:
  - code: '60,000'
    value: '${counters.icons}'
  - code: '60k'
    value: '${counters.icons-short}'
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'

Icon data

There are over 60,000 open source icons available, which you can use in your projects.

All these icons are:

Where to get them? {#sources}

To make it easier for developers to work with icons, there are several ways to get data for icons.

The main source of icon sets is iconify/icon-sets repository on GitHub. Icon sets are stored in [type]IconifyJSON format.

In addition to git repository, icon sets are available as:

Below is a description for each of those sources.

All icons

You can get the latest version of package from the following sources:

This package is big and might take a while to download.

See big icons package documentation for list of files, functions and usage examples.

Icon set list {#collections}

If you want to get a list of all available icon sets, it is:

See icon sets list for more details.

Individual icon sets {#json}

Each icon set is also published as a separate NPM package [npm]@iconify-json/{prefix} (where [str]{prefix} is an icon set prefix).

See split icon sets packages for more details.

API

Iconify API is very different from all other sources.

Other sources are various packages you can use during build time. Using them requires knowing which icons you are using, so build tools would extract data only for icons that you need. You cannot use them at run time because they are too big.

API is intended to be used when you don't know which icons you need. Several icon components retrieve icon data from API as needed, then render icon.

There are several downsides of using API to get icon data:

API also provides a list of available icon sets and icons, which can be used to build applications for browsing and searching icons, such as various plugins and icon pickers.

SVG

There are no special packages for SVG files, but you can generate them yourself using Iconify Tools.

In Iconify Tools examples, you can find a simple script that exports all icons as SVGs.

Icons

icon-set-basics

title: 'Getting Started: Icon Sets'
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
functions:
  getIconData: '/docs/libraries/utils/get-icon-data.md'
  parseIconSet: '/docs/libraries/utils/parse-icon-set.md'
  defaultIconProps: '/docs/libraries/utils/default-icon-props.md'

Icon Sets

What are icon sets?

Icon set is a set of icons, created by the same author or group of authors, published with the same name and license.

Examples

Several examples of icon sets:

All icons in an icon set must have the following in common:

Additionally, icons in open source icon sets have the following in common:

Format

In Iconify icons are not stored one by one as SVG, they are stored as icon sets in an easy to read custom JSON format, which uses [type]IconifyJSON type.

Advantages of using [type]IconifyJSON to store icon sets:

Naming

Each icon set has a prefix. It is unique for each icon set.

Prefix naming rules are the same as icon naming rules: allowed characters are [str]a-z, numbers and [str]-. Hyphen cannot be used at start or end of name, 2 hyphens in a row [str]-- are not allowed.

Examples of valid prefixes: [str]mdi, [str]mdi-light, [str]fluent-emoji-flat.

Functions

To parse icon sets, Iconify Utils offers the following functions:

To create convert icons to icon sets, use Iconify Tools.

Icons

icons

title: Split Icon Packages
types:
  IconifyIcon: '/docs/types/iconify-icon.md'
  IconifyInfo: '/docs/types/iconify-info.md'
functions:
  exportIconPackage: '/docs/libraries/tools/export/icon-package.md'

Split icon packages

For developer's convenience, full icon sets package was also available as smaller packages.

This documentation is for packages that contain many files, one per icon. These packages can be used if you need to import only few icons without parsing the whole icon set.

Packages

Packages are published as [npm]@iconify-icons/{prefix}, where [str]{prefix} is icon set prefix.

Packages are automatically generated from big icon sets package whenever it is updated.

Contents

Each package contains one icon set, with separate files for each icon ([str]{name} is icon name).

Icon data in [type]IconifyIcon format looks like this:

src: icons/sample.json
copy: false

You can import data for any icon using default import from file, like this:

import mdiHome from '@iconify-icons/mdi/home';

Example of React component using icon from such package:

src: icon-components/common/offline.jsx

Info

Additionally, each package contains default export with information about icon set in [type]IconifyInfo format.

Usage:

import mdiLightInfo from '@iconify-icons/mdi';

console.log('Icon set name:', mdiLightInfo.name);

Creating packages

If you want to create a package for your icon set, see [func]exportIconPackage() of Iconify Tools.

Icon sets list

If you need to get list of available open source icon sets, see icon sets list package.

Icons

index

title: "Getting Started: Icons"
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "60k"
    value: "${counters.icons-short}"
  - code: "80 icon sets"
    value: "${counters.sets} icon sets"
  - code: "80 open source"
    value: "${counters.sets} open source"
types:
  IconifyJSON: "/docs/types/iconify-json.md"
  IconifyIcon: "/docs/types/iconify-icon.md"

Icons

There are over 60,000 icons available from more than 80 open source icon sets, which you can use in your projects.

This section of Iconify documentation explains:

This section is only about icon data, it does not explain how to use icons in your project, for that see different section of documentation.

Icon data {#data}

How icons are organised:

See how to get icon data for a list of packages and repositories.

You can use that data to create your own components, plugins, generate icons in various formats.

Iconify ecosystem offers different components and plugins to render icons and tools to work with icons.

What makes Iconify different? {#iconify}

What makes Iconify different from other projects that consolidate icons?

See icon clean up and validation process article for more details. It also describes icon naming convention used in Iconify.

Icon sets

Icons in Iconify are organised in icon sets.

Each icon set has icons from the same author(s) following the same theme.

See icon set basics for more details.

Icon sets are automatically kept up to date, checking for updates several times a week.

Custom icons {#custom}

You can also use Iconify with custom icons.

This allows you to reuse components and plugins from Iconify ecosystem with your icons instead of creating your own.

See building custom icon sets for details.

Add an icon set {#add}

If you have created an open source icon set that you want to add to Iconify, please follow this guide.

Icons

json

title: Individual Icon Sets
types:
  IconifyJSON: "/docs/types/iconify-json.md"
  IconifyInfo: "/docs/types/iconify-json-metadata.md"
  IconifyChars: "/docs/types/iconify-json-metadata.md#chars"
  IconifyMetaData: "/docs/types/iconify-json-metadata.md#iconify-categories"
functions:
  exportJSONPackage: "/docs/libraries/tools/export/json-package.md"
  getIconData: "/docs/libraries/utils/get-icon-data.md"
  getIcons: "/docs/libraries/utils/get-icons.md"

Individual icon sets

For developer's convenience, full icon sets package is also available as smaller packages, one package per icon set.

Packages

Packages are published as [npm]@iconify-json/{prefix}, where [str]{prefix} is icon set prefix.

These packages are available only on NPM. They are automatically generated from big icon sets package whenever it is updated.

Contents

Unlike full package, where all data for icon set is stored in one file, individual icon sets split data in several files, so you can load only data you need:

You can import icon set using named import from package, like this:

import { icons as mdiIcons } from "@iconify-json/mdi";
import { icons as mdiLightIcons } from "@iconify-json/mdi-light";

Code samples above use JSON modules. It works fine when using bundlers or when using CommonJS. When using ES modules, older versions of Node.js require running script with [str]--experimental-json-modules flag.

If you are using older Node.js and cannot import JSON files, you can use [func]require():

const mdiIcons = require("@iconify-json/mdi/icons.json");
const mdiLightIcons = require("@iconify-json/mdi-light/icons.json");

Creating packages

If you want to create a package for your icon set, see [func]exportJSONPackage() of Iconify Tools.

Difference from big icon sets package

In big icon sets package, all JSON files contain an entire icon set: icon data, information, metadata (categories, themes), characters map.

In small packages that data is split into several files, as described above. If you only want icon data, it is better to read [file]icons.json from multiple small packages because they are smaller.

Icon sets list

If you need to get list of available open source icon sets, see icon sets list package.

Reading data {#tools}

For reading icon sets, you can use:

To use icon set packages with Iconify Utils, follow these steps:

Libraries

Libraries

index

title: Tools for Developers
types:
  IconifyJSON: '/docs/types/iconify-json.md'

Tools for developers

Iconify offers several libraries that help with converting icons, manipulating icon sets and generating icons.

Available libraries:

Utils

Iconify Utils is a set of reusable functions used by icon components and other packages. Its main purpose is to read [type]IconifyJSON icon sets and extract data from it.

The Iconify Utils package contains the following functions:

Additionally, it contains functions for:

Package works in any environment: node, browser, deno, and closed JavaScript environment.

Tools

Iconify Tools is a large package, its main purpose is to retrieve icons from various sources, validate them, clean them up and generate [type]IconifyJSON icon sets as well as various NPM packages.

The Iconify Tools package contains the following functions:

It is used to maintain available open source icon sets.

This package is designed to work only in Node.js. It is not usable in browser.

Libraries

iconify-icon

title: ResolvedIconifyIcon Type
types:
  IconifyIcon: '/docs/types/iconify-icon.md'
  FullIconifyIcon: '../utils/full-iconify-icon.md'
  IconSet: './icon-set/index.md'

ResolvedIconifyIcon type

[type]ResolvedIconifyIcon type is used in Iconify Utils.

It is [type]IconifyIcon with added optional properties that exist in both [type]ExtendedIconifyIcon and [type]ExtendedIconifyAlias. Currently, there is only one extra property:

Libraries

index

title: Iconify Tools
replacements:
  - code: "@iconify/tools@2"
    value: "${tools.import-tools2}"
types:
  IconifyIcon: "/docs/types/iconify-icon.md"
  IconifyJSON: "/docs/types/iconify-json.md"
  IconifyInfo: "/docs/types/iconify-info.md"
  FullIconifyIcon: "../utils/full-iconify-icon.md"
  Color: "../utils/color.md"
  FullIconCustomisations: "../utils/icon-customisations.md"
  IconCustomisations: "../utils/icon-customisations.md"
  SVG: "./svg/index.md"
  IconSet: "./icon-set/index.md"
functions:
  mergeIconSets: "./icon-set/merge.md"
  setIcon: "./icon-set/set-icon.md"
  cleanupSVG: "./icon/cleanup.md"

Iconify Tools

Iconify Tools is a set of reusable functions for importing, exporting, and parsing icons.

Library is written in TypeScript.

Installation

To install library run:

npm install @iconify/tools@2 --save

CommonJS support

The latest version does not support CommonJS.

If you need to use CommonJS, install version 4:

npm install @iconify/tools@cjs --save

Classes

include libraries/tools/main-classes

Import

To start working with an icon set, you can either create blank icon set or import icon set from some source.

Documentation from importing icons:

Before using Iconify Tools, you should be aware that package is opinionated. Certain tags are not allowed and will cause import to fail. See SVG import limitations.

Cleanup and validation

Cleaning up and validating icons is the first thing you should do after importing icons if icons come from:

See [func]cleanupSVG() documentation.

Manipulation

Iconify Tools offer several functions for manipulating icons. You can:

See icon manipulation functions for list of available functions.

Export

After manipulating icons, you can export icon set to various formats.

Documentation from exporting icons:

Package functions {#package}

In addition to managing icons, Iconify Tools has several functions to manage packages and repositories:

Libraries

tags

title: SVG validation in Iconify Tools

SVG validation in Iconify Tools

When importing SVG in Iconify Tools, there are some limitations, which cannot be changed.

Any icons containing the following will not be imported:

Iconify is very strict when it comes to security and quality. Icons should look identical for all users, regardless of browser and operating system.

Scripts

Not allowing scripts should be obvious. Scripts can be malicious. Also, scripts are not executed when icon is used as [func]url(), so they might not even work.

External resources

Relying on external resources is not ok:

There are no valid use cases for external resources in public SVG.

Raster images

SVGs are meant to scale. Raster images do not belong in SVG.

Text

Text is rendered differently in different browsers and operating systems. This is not acceptable. Icons should render identically for all users.

Convert text to vector shapes.

Libraries

export-svg

title: Export all Iconify icon sets as SVG

Export all Iconify icons as SVG

This example shows how to generate SVG files for all icons from [npm]@iconify/json package.

First, create a blank Node project, add [npm]@iconify/tools as a dependency.

Then create file [file]export-files.mjs and put this content:

src: libraries/tools/examples/export-all-files.mjs
title: 'export-files.mjs'

Then run that file:

node export-files.mjs
Libraries

import-fa-pro

title: Converting Font Awesome Pro to Iconify JSON

Converting Font Awesome Pro to Iconify JSON

Using the FontAwesome Pro git repository

This example shows how to convert FontAwesome Pro SVG files to Iconify JSON format.

Example assumes you have access to FontAwesome Pro repository. If you do have a valid license, you should have access to it.

Create file [file]convert-fa-pro.ts and put this content:

src: libraries/tools/examples/convert-fa-pro.ts
title: 'convert-fa-pro.ts'

Assuming that TypeScript is set to compile to [file]lib, compile file to JavaScript and run it:

node lib/convert-fa-pro

If you are not using TypeScript, remove types from code. It should not be hard because there aren't many lines to remove.

Prepared project is available in Iconify Tools GitHub repository.

Using the FontAwesome Pro npm libraries

An alternative way to generate the JSON files is using the NPM libraries provided by FontAwesome.

Example assumes you have access to FontAwesome Pro npm libraries. See the offficial guide if you don't have access to the libraries yet.

Create file [file]convert-fa-pro-npm.ts and put this content:

src: libraries/tools/examples/convert-fa-pro-npm.ts
title: 'convert-fa-pro-npm.ts'

If you are using NodeJs V22.6.0 or later you can run the TypeScript file natively.

node convert-fa-pro-npm.ts

If your NodeJs version is lower than v22.6.0 you need to add --experimental-strip-types to the command.

node --experimental-strip-types convert-fa-pro-npm.ts

Alternatively, you can manually remove the types from the code and run it as a JS file instead.

Libraries

import-figma

title: Exporting icon set from Figma with Iconify Tools

Exporting icons from Figma

This example shows how to import icon set from Figma, clean up all icons (including two-tone icons), export icon set as [type]IconifyJSON and SVG.

This specific code is designed to import and clean up Solar icon set.

Process

What is shown in this example?

This code has 3 parts:

What is happening in the clean-up process? For each icon it:

Code

src: libraries/tools/examples/import-solar.mjs
title: 'import-solar.mjs'
Libraries

import-mdi

title: Converting SVG set to Iconify JSON with Iconify Tools

Converting SVG set to Iconify JSON

This example shows how to convert directory full of SVG files to Iconify JSON format.

As a source, this example uses Material Design icons from Templarian/MaterialDesign-SVG repository that is also available as [npm]@mdi/svg NPM package.

Install dependencies:

npm install @iconify/tools @mdi/svg --save

Then create file [file]convert-mdi.ts and put this content:

src: libraries/tools/examples/convert-mdi.ts
title: 'convert-mdi.ts'

Assuming that TypeScript is set to compile to [file]lib, compile file to JavaScript and run it:

node lib/convert-mdi

If you are not using TypeScript, remove types from code. If should not be hard because there aren't many lines to remove.

Prepared project is available in Iconify Tools GitHub repository.

How does it work?

There are comments in the code above that explain what is going on.

The process is simple:

  1. [func]importDirectory() imports all icons from directory [str]"svg" of [npm]@mdi/svg package.
  2. [func]iconSet.forEach() is used to iterate all icons to:
    • [func]toSVG() is used to get SVG instance that can be manipulated by various functions.
    • [func]cleanupSVG() is used to clean up code (MDI has clean code, so nothing to clean up there, but for other icon sets it is needed).
    • [func]parseColors() is used to change default color to [str]currentColor.
    • [func]runSVGO() is used to optimise icon code.
    • [func]iconSet.fromSVG() is used to update icon data in icon set.
  3. Then script handles metadata: adds categories and aliases for all icons.
  4. [func]iconSet.export() is used to export icon set to JSON file.
Libraries

index

title: Iconify Tools Code Examples
types:
  IconifyJSON: '/docs/types/iconify-json.md'

Iconify Tools code examples

Short examples

Code samples are included in documentation for various functions. Some are short, some are longer.

The following code samples are short, yet complete enough to be usable:

Long examples

Several examples for specific icon sets:

Libraries

directory

title: Exporting Icons as SVG
types:
  SVG: '../svg/index.md'
  IconSet: '../icon-set/index.md'
  IconifyJSON: '/docs/types/iconify-json.md'
functions:
  export: '../icon-set/export.md'

Exporting icons to directory

This tutorial is part of export functions documentation in Iconify Tools.

Function [func]exportToDirectory() writes all icons in [type]IconSet instance to a specified directory.

Usage

Function has the following parameters:

Function returns array of stored icons.

Function is asynchronous. That means you need to handle it as [class]Promise instance, usually by adding [js]await before function call.

Options

The [prop]options object has the following mandatory property:

and the following optional properties:

Example

src: libraries/tools/export/directory.ts
title: 'example.ts'
Libraries

icon-package

title: Exporting Icon Packages
types:
  IconSet: '../icon-set/index.md'

Exporting icon set as icon package

This tutorial is part of export functions documentation in Iconify Tools.

Function [func]exportIconPackage() creates icon package in specified directory.

These packages are used in offline icon components, like this:

src: icon-components/common/offline.jsx

[npm]@iconify-icons/bi is a package generated by this function, used in example above.

See split icon packages documentation for details.

Deprecation notice

This function is deprecated, but it is still maintained for developers that do rely on it.

Single icon packages were needed in the early stages of Iconify project. In the modern Node ecosystem, this is no longer needed. Tools like Vite can be used to generate content on demand, including single file packages. Packages like Unplugin Icons dynamically generate icon components.

Single icon packages are no longer needed and should be avoided. If you need to extract data for few icons, do it during the build process of your app as either a custom script or a Vite plugin.

Usage

Function has the following parameters:

Function returns array of generated files.

Function is asynchronous. That means you need to handle it as [class]Promise instance, usually by adding [js]await before function call.

Options

The [prop]options object has the following mandatory property:

and the following optional properties:

customFiles

[prop]customFiles option contains additional files you want to add to package. Key is filename, value can be one of these types:

Example

src: libraries/tools/export/icon-package.ts
title: 'example.ts'
Libraries

index

title: Exporting icons
types:
  IconSet: '../icon-set/index.md'
  SVG: '../svg/index.md'
  IconifyJSON: '/docs/types/iconify-json.md'
functions:
  forEach: '../icon-set/for-each.md'
  cleanupSVG: '../icon/cleanup.md'
  runSVGO: '../icon/svgo.md'
  parseColors: '../icon/colors.md'
  deOptimisePaths: '../icon/paths.md'
  blankIconSet: '../icon-set/index.md'
  export: '../icon-set/export.md'
  toString: '../icon-set/to-string.md'
  exportToDirectory: './directory.md'
  exportIconPackage: './icon-package.md'
  exportJSONPackage: './json-package.md'

Exporting icons

Iconify Tools can export icons to several formats.

Usage

All functions listed below work with [type]IconSet instances. You need to create instance using [func]blankIconSet() or by using one of import functions.

Cleanup and optimisation

Before exporting icons, make sure you clean them up and optimise.

See icon manipulation functions.

Export functions

There are several functions for exporting icons:

Exporting Iconify icon set {#json}

[type]IconSet instance has [func]export() function that creates [type]IconifyJSON data. All you have to do is write it to file.

See exporting Iconify icon set documentation.

Exporting SVG (simplified version) {#directory}

Function [func]exportToDirectory() exports all icons as SVG to a directory.

Exporting as SVG {#svg}

[type]IconSet instance has [func]toString() function that generates [type]string for icon. You can use [func]forEach() to loop all icons in icon set.

See exporting icons as SVG documentation.

Exporting NPM packages {#npm}

There are different types of icon packages published at NPM, there are functions for exporting each type:

Functions do not publish packages, they only generate contents. Run [bash]npm publish to publish generated packages.

Libraries

json-package

title: Exporting JSON Packages
types:
  IconSet: '../icon-set/index.md'
  IconifyJSON: '/docs/types/iconify-json.md'

Exporting icon set as JSON package

This tutorial is part of export functions documentation in Iconify Tools.

Function [func]exportJSONPackage() creates an icon package in specified directory.

These packages are used to load an entire icon sets, like this:

import { addCollection, Icon } from '@iconify/react';
import { icons as mdiLightIcons } from '@iconify-json/mdi-light';
import { icons as tablerIcons } from '@iconify-json/tabler';

addCollection(mdiLightIcons);
addCollection(tablerIcons);

// Demo using some of imported icons
export function renderHomeIcon() {
	return <Icon icon="mdi-light:home" />;
}

export function renderAlertIcon() {
	return <Icon icon="tabler:alert-octagon" />;
}

[npm]@iconify-json/mdi-light and [npm]@iconify-json/tabler are packages generated by this function, used in example above.

See individual icon set packages documentation for details.

Usage

Function has the following parameters:

Function returns array of generated files.

Function is asynchronous. That means you need to handle it as [class]Promise instance, usually by adding [js]await before function call.

Options

Options object has the following mandatory property:

and the following optional properties:

customFiles

[prop]customFiles option contains additional files you want to add to package. Key is filename, value can be one of these types:

Example

src: libraries/tools/export/json-package.ts
title: 'example.ts'
Libraries

json

title: Exporting Iconify Icon Set
types:
  SVG: '../svg/index.md'
  IconSet: '../icon-set/index.md'
  IconifyJSON: '/docs/types/iconify-json.md'
functions:
  export: '../icon-set/export.md'

Exporting Iconify icon set

This tutorial is part of export functions documentation in Iconify Tools.

[type]IconSet instance has [func]export() function that exports icon set in [type]IconifyJSON format.

Then you need to convert it to string using [func]JSON.stringify() and save it to file.

Example

src: libraries/tools/export/json.ts
title: 'example.ts'
Libraries

svg

title: Exporting Icons as SVG
types:
  SVG: '../svg/index.md'
  IconSet: '../icon-set/index.md'
  IconifyJSON: '/docs/types/iconify-json.md'
functions:
  toString: '../icon-set/to-string.md'
  forEach: '../icon-set/for-each.md'

Exporting SVG

This tutorial is part of export functions documentation in Iconify Tools.

[type]IconSet instance has [func]toString() function that exports icon as [type]string. You can use [func]forEach() to loop all icons in icon set.

Example

src: libraries/tools/export/svg.ts
title: 'example.ts'
Libraries

cleanup

title: Cleaning up and validating SVG
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyInfo: '/docs/types/iconify-info.md'
  SVG: '../svg/index.md'
  IconSet: '../icon-set/index.md'
functions:
  validateIconSet: '../../utils/validate-icon-set.md'

Icon cleanup and validation

Cleanup functions are used in Iconify Tools to validate and clean up imported icons.

Unfortunately, many editors leave lots of junk in SVG files, sometimes multiplying icon file size several times.

SVG files might also contain scripts and links to external resources.

Usage

To clean up and validate icon, run [func]cleanupSVG().

Function has one required parameter:

and one optional parameter:

Function does not return anything, it applies changes to [type]SVG instance.

On error function will throw an exception.

Options

The [prop]options parameter has the following properties:

Titles are removed by default because almost all icons can represent many things, therefore, hardcoded titles are not usable for most users. The option to keep titles is intended for working with custom icon sets that are specific to one website.

Clean up process

Clean up process runs several functions that do various tasks:

If you want to, you can run functions listed above, in order listed above. It will be identical to running [func]cleanupSVG().

Optimisation

Clean up functions do not optimise icon data, they do not rewrite any shapes. Functions only remove most dead code, making it easier to process icon.

Optimisation should be done separately. See icon manipulation functions.

Opinionated validation

Validation is opinionated. It is intended to be used to produce icons that are available to anyone, therefore, it is rather strict.

Icon validation fails if icon:

Example

src: libraries/tools/svg/cleanup.ts
title: 'cleanup.ts'
extra:
  - src: libraries/tools/svg/cleanup.svg
    title: 'Result:'
Libraries

colors

title: Changing colors in SVG
types:
  SVG: '../svg/index.md'
  IconSet: '../icon-set/index.md'
  Color: '../../utils/color.md'
functions:
  stringToColor: '../../utils/string-to-color.md'
  colorToString: '../../utils/color-to-string.md'

Parsing colors in SVG

This function is part of icon manipulation functions in Iconify Tools.

Function [func]parseColors() parses colors in SVG.

It can:

Function parses colors in:

Function does not parse colors in:

Usage

Function has the following parameters:

Function returns array of colors.

Colors

Colors used in callback and returned by function can be two types:

Options

The [prop]options object has the following properties:

Default color

Some icons use system color. Example:

<svg viewBox="0 0 1200 400" xmlns="http://www.w3.org/2000/svg" width="1200" height="400">
    <path d="M300 200H150A150 150 0 10300 50z"/>
</svg>

In that icon path uses default fill. In Iconify all icons should use colors set by [prop]color attribute, which means shapes should use [str]currentColor for fill.

If you set [prop]defaultColor option, parser will automatically set color for shapes that use default color.

Example:

src: libraries/tools/icon/color-default.ts
title: 'default-color.ts'
extra:
  - src: libraries/tools/icon/color-default.svg
    title: 'Result:'

Replacing colors

With [prop]callback option you can replace colors.

Callback has the following parameters:

Callback should return:

Example

src: libraries/tools/icon/colors.ts
title: 'example.ts'
extra:
  - src: libraries/tools/icon/colors.json
    title: 'Result:'
Libraries

index

title: Changing icon content
types:
  IconSet: '../icon-set/index.md'
  SVG: '../svg/index.md'
functions:
  list: '../icon-set/list.md'
  forEach: '../icon-set/for-each.md'
  cleanupSVG: './cleanup.md'
  runSVGO: './svgo.md'
  parseColors: './colors.md'
  deOptimisePaths: './paths.md'
  scaleSVG: './scale.md'
  convertSVGToMask: './mask.md'

Changing icon content

Before exporting icons, you need to properly fix them. Iconify Tools offers many functions for manipulating icon content: fixing various issues, optimising code, changing palette.

Usage

All functions listed below work with [type]SVG instances.

Working with icon sets

How to use functions to parse all icons in an icon set?

It can be done by using [func]forEach() and [func]forEachSync() methods:

src: libraries/tools/icon/icon-set.ts

Cleanup

Before running any icon manipulation function, you should validate and clean up icon. See [func]cleanupSVG() function.

Functions

There are several functions for manipulating icons:

runSVGO()

Function [func]runSVGO() optimises icon.

Cleaning up icons with [func]cleanupSVG() is not enough. That function is very basic; it does bare minimum to get rid of bad stuff. It is mostly for validation.

Use [func]runSVGO() to properly clean up and optimise icons.

parseColors()

Function [func]parseColors() is used to analyze icon's palette or change it.

Usually icons either do not have palette, relying on [prop]fill style or use black colors. Neither option is acceptable for using icons with Iconify. Iconify all icons that do not have hardcoded palette should use [prop]currentColor.

This function can be used to change colors, make sure icon does not have colors it is not supposed to have, add colors to shapes that rely on default colors.

deOptimisePaths()

Function [func]deOptimisePaths() makes sure icon would work with old software.

All browsers support modern SVG, which include compressed arcs in [tag]path elements. However, there is plenty of software that does not. Usually it is image editing software that rely on ancient SVG parsing libraries.

scaleSVG()

Function [func]scaleSVG() changes icon dimensions.

resetSVGOrigin()

Function [func]resetSVGOrigin() shifts top left corner of [prop]viewBox to 0.

removeFigmaClipPathFromSVG()

Function [func]removeFigmaClipPathFromSVG() attempts to remove unnecessary clip paths, which are often added when icon is exported in Figma.

convertSVGToMask()

Function [func]convertSVGToMask() converts icon content to mask.

This is useful if you want to change icon with multiple colors into a monotone icon, using source colors as shades.

Libraries

mask

title: Convert SVG to mask
types:
  SVG: '../svg/index.md'
  IconSet: '../icon-set/index.md'
functions:
  #parseColors: './colors/parse.md'

Converting SVG to mask

This function is part of icon manipulation functions in Iconify Tools.

Function [func]convertSVGToMask() converts icon content to an alpha mask and masks a rectangle that has the same dimensions as icon's [prop]viewBox.

This function is intended to be used in two scenarios:

How masks work

Masks help in a situation when there are multiple shapes, some of which should be solid, some transparent. Image in a mask is treated as an alpha channel for shape that is being masked.

Color in shapes is treated as an alpha channel: white (255) has opacity of 1, black (0) has opacity of 0. Other colors are converted to alpha channel by combining their red, green and blue channels are dividing it by 255*3.

For example, this icon has multiple shapes with different colors (using black background to make sure white shapes are visible):

Here is the same icon used as a mask for rectangle, rendered using various colors:

Code used to create this sample is available below in the examples section, in "Converting as is" demo.

Usage

Function has the following parameters:

Function returns true on success, false if icon was not converted to mask.

False result

When can function fail to convert icon to mask?

Options

Options is an object with the following optional properties:

To tell function which colors should be treated as solid, transparent or semi-transparent, use the following options:

By default, black color is considered to be solid, white color is considered to be transparent (opposite of how masks work, but exactly how most bugged icons are designed), all other colors found in an icon will cause function to fail.

When using [prop]custom option, you might want to disable default values for [prop]solid and [prop]transparent options if [prop]custom does not handle unknown colors. To do that, set them to empty arrays.

Solid and transparent

[prop]solid and [prop]transparent can be:

Color values and color passed to callback are always in lower case. So, if your icon uses [str]#FFF, check for [str]#fff.

Custom

[prop]custom property is used when both [prop]solid and [prop]transparent return false.

It is a function with 2 parameters:

Function can return:

Default values for [prop]solid and [prop]transparent properties might interfere with [prop]custom property, so set them to either an empty array or a callback that always returns false.

Examples

The following examples show how to use function.

Fix black/white

This example fixes badly designed icons, which use black color for solid shapes, white color for transparent shapes.

Such icons are widespread in icon sets available in Figma community resources: designers use white background for pages and don't notice that shapes contain white colors because outside of an icon background is also white.

src: libraries/tools/icon/mask-white.ts
title: 'example.ts'
extra:
  - src: libraries/tools/icon/mask-white.svg
    title: 'Result:'

If instead of black color, icon is designed using another color, such as [str]#1C274C, add it to [prop]solid option in lower case:

convertSVGToMask(svg, {
	solid: ['#000', 'black', '#1c274c']
});

Converting as is

This example masks an icon without changing any colors. It is used to create mask sample used at the beginning of this page:

src: libraries/tools/icon/mask-demo.ts
title: 'example.ts'

Demo of this icon is available above in "How masks work" section.

Multiple colors

Sometimes icons are designed with multiple colors. This function can be used to convert them to monotone icons, using different colors as solid, semi-transparent or transparent colors.

This can be done using [prop]custom option.

Example (using gray background for original icon to make sure both black and white shapes are visible):

The following code converts icon to monotone icon, rendering black shapes as solid, blue and white as different semi-transparent:

src: libraries/tools/icon/mask-colors.ts
title: 'example.ts'

Result:

Advanced example

How to parse an entire icon set and check for errors?

This can be done using functions [func]forEach() or [func]forEachSync() of [type]IconSet instance. Both functions are suitable, but because masks are applied synchronously, there is no reason to use async functions, so [func]forEachSync() is a better choice.

See very long example for importing icon set from Figma for code.

In that example, [func]convertSVGToMask() is used after all colors are parsed with [func]parseColors(). If, when parsing colors, white or semi-transparent colors are found, [func]convertSVGToMask() is called to convert icon to mask.

Libraries

paths

title: Fixing compatibility with old SVG parsers
types:
  SVG: '../svg/index.md'
  IconSet: '../icon-set/index.md'

Compatibility with old SVG parsers

This function is part of icon manipulation functions in Iconify Tools.

Function [func]deOptimisePaths() checks [tag]path elements for syntax that might not be supported by older software and automatically fixes it.

Unfortunately, a lot of software, such as image editing software, uses old libraries for parsing SVG. Those libraries do not support compressing arcs in paths, resulting in incorrectly imported icons. Compressing arcs doesn't make much different in icon size, so better to have icons usable in all software than save a couple of bytes.

Usage

Function has only one parameter:

Function does not return anything, it applies changes to [type]SVG instance.

Example

src: libraries/tools/icon/paths.ts
title: 'example.ts'
extra:
  - src: libraries/tools/icon/paths.svg
    title: 'Result:'

As you can see from an example, changes are minor. However, not applying these minor changes might break icon for many users that use old software, so better run this function on all icons before exporting.

Make sure you do not run SVGO optimisation after running this function because SVGO might compress paths.

Libraries

scale

title: Scale SVG
types:
  SVG: '../svg/index.md'
  IconSet: '../icon-set/index.md'

Scaling SVG

This function is part of icon manipulation functions in Iconify Tools.

Function [func]scaleSVG() changes icon size.

For most icons this function is not needed, you can change size by changing [prop]width and [prop]height properties, but it is available anyway.

Usage

Function has the following parameters:

Example

src: libraries/tools/icon/scale.ts
title: 'svgo.ts'
extra:
  - src: libraries/tools/icon/scale.svg
    title: 'Result:'
Libraries

svgo

title: Optimising SVG
functions:
  cleanupSVG: './cleanup.md'
types:
  SVG: '../svg/index.md'
  IconSet: '../icon-set/index.md'

Optimising icon with SVGO

This function is part of icon manipulation functions in Iconify Tools.

Function [func]runSVGO() optimises icon using popular SVG optimisation tool SVGO.

It is meant to be used on icons that have already been processed with [func]cleanupSVG(), which does most of the cleanup.

This function is used to do advanced stuff that SVGO is good at: converting transformations, cleaning up numbers, removing unused SVG elements, and so on.

Plugins

By default, function uses a pre-configured list of SVGO plugins, which excludes some bugged plugins.

If an icon contains SVG animations, plugins that modify shapes are excluded.

Usage

Function has the following parameters:

Options

There are two ways to set options:

Custom plugins list

You can set custom plugins using [prop]plugins property of options. Value is array of plugins, passed directly to SVGO (see SVGO documentation).

Example:

runSVGO(svg, {
	plugins: ['convertStyleToAttrs', 'inlineStyles'],
	multipass: true,
});

Plugin options

You can also pick from a preset list of plugins by setting these options:

These options cannot be used together with [prop]plugins option.

Other options

Options that can be used with any options listed above:

Example

src: libraries/tools/icon/svgo.ts
title: 'svgo.ts'
extra:
  - src: libraries/tools/icon/svgo.svg
    title: 'Result:'

That example shows running SVGO on icon that has not been cleaned up and validated. Not all useless attributes have been removed, and SVGO doesn't check for some content that should not be in icon, such as text, raster images and events.

Therefore, all icons must be cleaned up after loading.

Same code with clean up:

src: libraries/tools/icon/svgo2.ts
title: 'svgo.ts'
extra:
  - src: libraries/tools/icon/svgo2.svg
    title: 'Result:'
Libraries

categories

title: Categories data in icon set
types:
  IconSet: './index.md'
  IconCategory: './categories.md#type'
functions:
  listCategory: './list-category.md'

categories

This property is part of [type]IconSet class in Iconify Tools.

Property [prop]categories contains list of categories.

Structure

Property [prop]categories is a [type]Set of [type]IconCategory entries.

IconCategory type {#type}

Type [type]IconCategory has the following properties:

Number of icons is approximate, to get exact number use [func]listCategory() function. Running [func]listCategory() updates [type]IconCategory entry and deletes empty categories.

Libraries

chars

title: Export characters map from icon set
types:
  IconSet: './index.md'
  IconifyJSON: '/docs/types/iconify-json.md'
functions:
  export: './export.md'
  toggleCharacter: './toggle-character.md'

chars()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]chars() exports characters map. Function is used by [func]export() function to add characters map to [type]IconifyJSON data.

Usage

Function has one parameter:

Function returns a simple [type]Record<string, string> object. Key is character, in hexadecimal form (such as [str]u1f3cc), value is name of icon.

Character map

What is the purpose of characters map?

It is used to generate icon fonts. Each icon in an icon font has a character assigned to it. Even when using ligatures, ligatures point to a character, so character is needed.

How to assign a character to icon? {#assign}

You can assign a character to icon by using [func]toggleCharacter() method.

Example

src: libraries/tools/icon-set/chars.ts
title: 'chars-example.ts'
extra:
  - src: libraries/tools/icon-set/chars1.json
    title: 'chars() result:'
  - src: libraries/tools/icon-set/chars2.json
    title: 'export() result:'
Libraries

check-theme

title: Checking themes in icon set
types:
  IconSet: './index.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
  ResolvedIconifyIcon: '../iconify-icon.md'
  CommonIconProps: './entries.md#common'
functions:
  themes: './themes.md'
  prefixes: './themes.md'
  suffixes: './themes.md'
  export: './export.md'

checkTheme()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]checkTheme() finds all icons that belong to theme. It can be used to validate themes to make sure there are no empty or missing themes.

Usage

Function has the following parameter:

Function returns an object with the following properties:

Example

src: libraries/tools/icon-set/check-theme.ts
title: 'example.ts'
extra:
  - src: libraries/tools/icon-set/check-theme1.json
    title: 'Results:'
  - src: libraries/tools/icon-set/check-theme2.json
Libraries

count

title: Count icons in icon set
types:
  IconSet: './index.md'

count()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]count() counts icons in icon set.

Usage

Function has no parameters.

Function returns [type]number of icons.

What icons are counted? {#logic}

Counted:

Not counted:

Icon types

include libraries/tools/icon-set/icon-types

Example

src: libraries/tools/icon-set/count.ts
title: 'example.ts'
Libraries

entries

title: Icons data in icon set
types:
  IconSet: './index.md'
  IconSetIconEntry: './entries.md#type'
  IconifyIcon: '/docs/types/iconify-icon.md'
  IconCategory: './categories.md'
  CommonIconProps: './entries.md#common'
functions:
  setItem: './set-item.md'
  setIcon: './set-icon.md'
  setVariation: './set-variation.md'
  setAlias: './set-alias.md'
  remove: './remove.md'
  rename: './rename.md'
  categories: './categories.md'

entries

This property is part of [type]IconSet class in Iconify Tools.

Property [prop]entries contains data for all icons.

Avoid accessing [prop]entries if you can, use the following functions instead:

Icon types

include libraries/tools/icon-set/icon-types

Structure

Property [prop]entries is a simple object, where key is icon name and value is [type]IconSetIconEntry entry.

IconSetIconEntry type {#type}

Type [type]IconSetIconEntry is a set of 3 types:

To check the type, access [prop]type property of icon data.

Properties

The following properties exist only in [type]IconSetIcon type:

The following properties exist on [type]IconSetIcon and [type]IconSetIconVariation types:

The following properties exist on [type]IconSetIconVariation and [type]IconSetIconAlias types:

The following properties exist on all types:

CommonIconProps type {#common}

Type [type]CommonIconProps is mix of common properties that exist in both [type]ExtendedIconifyIcon and [type]ExtendedIconifyAlias types. It is almost identical to [type]IconifyIcon type, but with small differences:

Libraries

exists

title: Check if icon exists in icon set
types:
  IconSet: './index.md'
functions:
  export: './export.md'

exists()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]exists() checks if icon is in icon set, returns [type]boolean value.

Usage

Function has the parameter:

Libraries

export

title: Export icon set
types:
  IconSet: './index.md'
  IconifyJSON: '/docs/types/iconify-json.md'

export()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]export() exports icon set as [type]IconifyJSON object.

Usage

Function has the following parameters:

Function returns [type]IconifyJSON object.

Result includes all metadata. If icon set has information property, export will automatically update total number of icons in info block.

Example

src: libraries/tools/icon-set/export.ts
title: 'example.ts'
extra:
  - src: libraries/tools/icon-set/export.json
    title: 'Result:'
Libraries

for-each

title: Iterate icons in icon set
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconSet: './index.md'
functions:
  mergeIconSets: './merge.md'

forEach()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]forEach() runs a custom callback for all icons in icon set.

Function supports asynchronous callbacks.

If you use synchronous callback, you can treat function as synchronous, or you can use [func]forEachSync() alias.

Usage

Function has the following parameters:

Callback

Callback can be synchronous or async. It has the following parameters:

If callback returns false, function stops iterating icons.

Icon types

include libraries/tools/icon-set/icon-types

Example

src: libraries/tools/icon-set/for-each.ts
title: 'example.ts'
extra:
  - src: libraries/tools/icon-set/for-each.txt
    title: 'Result:'
Libraries

from-svg

title: Import icon from SVG to icon set
types:
  IconSet: './index.md'
  SVG: '../svg/index.md'

fromSVG()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]fromSVG() imports icon from [type]SVG instance to [type]IconSet icon set. It can be used to add a new icon or replace an existing icon.

Usage

Function has the following parameters:

Function returns true on success, false on failure.

Example

src: libraries/tools/icon-set/to-svg.ts
title: 'example.ts'
extra:
  - src: libraries/tools/icon-set/to-svg.svg
    title: 'Result:'
Libraries

get-tree

title: Get icon dependencies tree from icon set
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconSet: './index.md'

getTree()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]getTree() returns list of parent icons for each icon in icon set, null for icons that cannot be resolved.

It is useful when you need to figure out which icons need to be exported when exporting a subset of icons, it can be used to figure out which icons have invalid parent icons.

Usage

Function has the following optional parameter:

Function will return object, where key is icon name, value is:

Example

src: libraries/tools/icon-set/get-tree.ts
title: 'example.ts'
extra:
  - src: libraries/tools/icon-set/get-tree.json
    title: 'Result:'
Libraries

index

title: IconSet Class
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyInfo: '/docs/types/iconify-info.md'
functions:
  validateIconSet: '../../utils/validate-icon-set.md'
  forEach: './for-each.md'
  forEachSync: './for-each.md'

IconSet class

[type]IconSet class in Iconify Tools represents an icon set.

Usage

To create an instance, use this code to import existing [type]IconifyJSON data:

import { IconSet } from '@iconify/tools';

const iconSet = new IconSet({
	prefix: 'codicon',
	icons: {
		'add': {
			body: '<g fill="currentColor"><path d="M14 7v1H8v6H7V8H1V7h6V1h1v6h6z"/></g>',
		},
		'chrome-maximize': {
			body: '<g fill="currentColor"><path d="M3 3v10h10V3H3zm9 9H4V4h8v8z"/></g>',
		},
		'chrome-minimize': {
			body: '<g fill="currentColor"><path d="M14 8v1H3V8h11z"/></g>',
		},
	},
});

or this to create an empty icon set:

import { blankIconSet } from '@iconify/tools';

const iconSet = blankIconSet('some-prefix');

Constructor does not validate the icon set. If you are not sure about the source, you need to validate it using [func]validateIconSet() from Iconify Utils.

Functions

include libraries/tools/icon-set/methods-list

Working with icons

All icon optimisation and parsing functions work with [type]SVG instances. How to apply those functions to an entire icon set?

It can be done by icons using [func]forEach() method:

src: libraries/tools/icon/icon-set.ts
Libraries

info

title: Icon set information
types:
  IconSet: './index.md'
  IconifyInfo: '/docs/types/iconify-info.md'
functions:
  export: './export.md'

info

This property is part of [type]IconSet class in Iconify Tools.

Property [prop]info contains icon set information in [type]IconifyInfo format. It includes icon set name, license, author information and some other data relevant when displaying an icon set.

If an icon set does not have the information block, value is [type]null.

You can write to property directly to update value.

Value

Value is used when exporting icon set using [func]export() function.

Icons count in [prop]info property is automatically updated when running [func]export() function, so no need to update it manually.

Libraries

list-category

title: List icons in category in icon set
types:
  IconSet: './index.md'
  IconifyJSON: '/docs/types/iconify-json.md'
  IconCategory: './categories.md#type'
functions:
  categories: './categories.md'

listCategory()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]listCategory() lists icons that belong to a category.

Categories are used to filter icons when displaying icon set.

Usage

Function has the following parameter:

Function returns [type]string[] array of icon names.

Result does not include:

This function automatically updates [prop]count property of [type]IconCategory item. If category is empty, category is removed from [func]categories property of icon set.

Example

src: libraries/tools/icon-set/list-category.ts
title: 'example.ts'
Libraries

list

title: List icons in icon set
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconSet: './index.md'
functions:
  mergeIconSets: './merge.md'

list()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]list() lists all icons in an icon set.

Usage

The function has the following parameter:

Function returns an array of icon names [type]string[].

Icon types

include libraries/tools/icon-set/icon-types

Example

src: libraries/tools/icon-set/list.ts
title: 'example.ts'
extra:
  - src: libraries/tools/icon-set/list.json
    title: 'Result of export():'
Libraries

load

title: Load icon set
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconSet: './index.md'
functions:
  mergeIconSets: '../index.md'
  validateIconSet: '../../utils/validate-icon-set.md'

load()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]load() loads icon set from [type]IconifyJSON data.

It replaces existing icon set data, so it is identical to creating new [type]IconSet instance. If you want to merge icon sets instead, see [func]mergeIconSets() function.

Validation

Function does not validate icon set. If you are not sure about source, you need to validate it using [func]validateIconSet() from Iconify Utils.

Example

src: libraries/tools/icon-set/load.ts
title: 'example.ts'
Libraries

merge

title: Merge icon sets with Iconify Tools
types:
  IconSet: './index.md'

mergeIconSets()

This function is part of Iconify Tools package.

Function [func]mergeIconSets() merges to icon sets, creating new [type]IconSet instance.

Why merge icon sets?

When you update an icon set, often old icons are lost. If someone is using an old icon, which no longer exists or was renamed, removing that icon will result in a broken UI. This is why icons should never be removed.

Merging new icon set and old icon set ensures that icons are never removed. Merge process adds missing icons, but marks them as hidden, so they are not shown in icons list, but are available to anyone using old icons.

This function attempts to detect renamed icons, creating aliases for those icons.

Usage

Function has the following parameters:

Function does not modify icon sets passed in parameters, it creates new [type]IconSet instance and returns it.

Example

src: libraries/tools/merge-icon-sets.ts
title: 'example.ts'
extra:
  - src: libraries/tools/merge-icon-sets.json
    title: 'Result:'
Libraries

prefix

title: Icon set prefix
types:
  IconSet: './index.md'

prefix

This property is part of [type]IconSet class in Iconify Tools.

Property [prop]prefix contains icon set prefix, [type]string.

You can write to property directly to update value.

Libraries

remove

title: Remove icon from icon set
types:
  IconSet: './index.md'
  SVG: '../svg/index.md'

remove()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]remove() deletes an icon.

Usage

Function has the following parameters:

Function returns [type]number of removed items.

Possible values for [prop]removeDependencies property:

Example

src: libraries/tools/icon-set/remove.ts
title: 'example.ts'
extra:
  - src: libraries/tools/icon-set/remove.json
    title: 'Result:'
Libraries

rename

title: Rename icon in icon set
types:
  IconSet: './index.md'
  IconifyJSON: '/docs/types/iconify-json.md'
functions:
  export: './export.md'
  toggleCharacter: './toggle-character.md'

rename()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]rename() renames icon.

Function checks aliases and variations that use renamed icon, changes parent icon to new name.

If icon with new name already exists, it will be overwritten.

Usage

Function has the following parameters:

Function returns a simple true on success, false on failure.

Example

src: libraries/tools/icon-set/rename.ts
title: 'example.ts'
extra:
  - src: libraries/tools/icon-set/rename.json
    title: 'Result:'
Libraries

resolve

title: Resolve icon in icon set
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
  FullIconifyIcon: '../../utils/full-iconify-icon.md'
  IconSet: './index.md'

resolve()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]resolve() retrieve data for icon in [type]IconifyIcon format.

Usage

Function has the following parameters:

Function returns [type]IconifyIcon (or [type]FullIconifyIcon if second parameter is true), [type]null on error.

Example

src: libraries/tools/icon-set/resolve.ts
title: 'example.ts'
extra:
  - src: libraries/tools/icon-set/resolve1.json
    title: 'Results for "debug-pause":'
  - src: libraries/tools/icon-set/resolve2.json
  - src: libraries/tools/icon-set/resolve3.json
    title: 'Results for "triangle-right":'
  - src: libraries/tools/icon-set/resolve4.json
  - src: libraries/tools/icon-set/resolve5.json
    title: 'Results for "plus":'
  - src: libraries/tools/icon-set/resolve6.json
Libraries

set-alias

title: Add icon alias to icon set
types:
  IconSet: './index.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
functions:
  setIcon: './set-icon.md'
  setVariation: './set-variation.md'
  setAlias: './set-alias.md'

setAlias()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]setAlias() adds new icon alias.

Alias

Icon alias is a different name for icon. It is usually used when renaming icon to allow users access icon using old name.

Usage

Function has the following parameters:

Function returns a simple true on success, false on failure.

Example

src: libraries/tools/icon-set/set-alias.ts
title: 'example.ts'
extra:
  - src: libraries/tools/icon-set/set-alias.json
    title: 'Result:'
Libraries

set-icon

title: Add icon to icon set
types:
  IconSet: './index.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
  ResolvedIconifyIcon: '../iconify-icon.md'
functions:
  setIcon: './set-icon.md'
  setVariation: './set-variation.md'
  setAlias: './set-alias.md'

setIcon()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]setIcon() adds new icon to icon set or overwrites existing item.

Usage

Function has the following parameters:

Function returns a simple true on success, false on failure.

Example

src: libraries/tools/icon-set/export.ts
title: 'example.ts'
Libraries

set-item

title: Add item to icon set
types:
  IconSet: './index.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
  IconSetIconEntry: './entries.md#type'
functions:
  setIcon: './set-icon.md'
  setVariation: './set-variation.md'
  setAlias: './set-alias.md'

setItem()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]setItem() adds new item to icon set or overwrites existing item. If item is an alias or variation, function checks for parent icon.

This function is not simple to use. Better use one of simpler functions:

Usage

Function has the following parameters:

Function returns a simple true on success, false on failure.

Libraries

set-variation

title: Add icon variation to icon set
types:
  IconSet: './index.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
  ResolvedIconifyIcon: '../iconify-icon.md'
  CommonIconProps: './entries.md#common'
functions:
  setIcon: './set-icon.md'
  setVariation: './set-variation.md'
  setAlias: './set-alias.md'

setVariation()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]setVariation() adds new icon variation to icon set or overwrites existing item.

Variation

Icon variation is an item that is based on different icon, but has at least one transformation applied to it.

For example, [str]arrow-left can be a variation of [str]arrow-right with [prop]hFlip enabled.

Variations make it easier to maintain icons that are based on other icons and reduce content duplication.

Usage

Function has the following parameters:

Function returns a simple true on success, false on failure.

Example

src: libraries/tools/icon-set/set-alias.ts
title: 'example.ts'
extra:
  - src: libraries/tools/icon-set/set-alias.json
    title: 'Result:'
Libraries

themes

title: Icon set themes
types:
  IconSet: './index.md'
functions:
  checkTheme: './check-theme.md'

Themes

Theme properties are part of [type]IconSet class in Iconify Tools.

Themes are used to quickly place icons in categories based on part of icon name without listing every single icon.

There are two properties:

You can write to properties directly to update values.

Structure

Both are simple objects [type]Record<string, string>, where:

Examples

Examples below show suffixes. Prefixes work just like suffixes, but compare first part of icon.

Example of suffixes list:

{
	"line": "Line",
	"solid": "Solid"
}

Prefixes and suffixes should not start or end with [str]-.

All icons that end with [str]-line belong to [str]Line category, all icons that end with [str]-solid belong to [str]Solid category.

If icon ends with something else, like [str]-outline, it will not belong to [str]Line category because icons are checked for [js]'-' + suffix (or [js]prefix + '-' for prefixes).

Multiple similar items

There can be multiple matching suffixes, such as [str]24-line and [str]line.

There can also be empty suffix (and prefix), which matches icons that do not match other suffixes.

Example of suffixes:

{
	"24-line": "Line 24",
	"line": "Line",
	"": "Other"
}

Icon [str]home-24-line will belong to [str]Line 24 suffix, icon [str]home-20-line will belong to [str]Line suffix, icon [str]home-solid will belong to [str]Other suffix.

Order of suffixes and prefixes does not matter. They are sorted by length (longest first) before matching icons to make sure icons are placed in correct theme regardless of order.

Finding icons

To find which icons belong to which theme, use [func]checkTheme() function.

Libraries

to-string

title: Convert icon to string in icon set
types:
  IconSet: './index.md'
  IconifyIconCustomisations: '../../utils/icon-customisations.md'

toString()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]toString() exports icon as string.

Usage

Function has the following parameters:

Function returns rendered icon as [type]string on success, [type]null if icon does not exist.

Customisations

If [prop]customisations is not set, default value is:

{
	"width": "auto",
	"height": "auto"
}

which results in [prop]width and [prop]height of icon matching [prop]viewBox (see example below).

If you want to use [num]1em height, use the following [prop]customisations:

{
	"height": "1em"
}

Example

src: libraries/tools/icon-set/to-string.ts
title: 'example.ts'
extra:
  - src: libraries/tools/icon-set/to-string.svg
    title: 'Result:'
Libraries

to-svg

title: Export icon as SVG instance in icon set
types:
  IconSet: './index.md'
  SVG: '../svg/index.md'
functions:
  fromSVG: './from-svg.md'

toSVG()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]toSVG() exports icon as [type]SVG instance.

It is used to process icon using functions that work with [type]SVG instances.

Important notice

[type]SVG instance is not synchronised with an icon set.

After changing icon, you need to update entry in [type]IconSet using [func]fromSVG() method.

Usage

The function has the following parameter:

Function returns [type]SVG instance on success, [type]null on error.

Example

src: libraries/tools/icon-set/to-svg.ts
title: 'example.ts'
extra:
  - src: libraries/tools/icon-set/to-svg.svg
    title: 'Result:'
Libraries

toggle-category

title: Assign category to icons in icon set
types:
  IconSet: './index.md'
  IconifyJSON: '/docs/types/iconify-json.md'
  IconCategory: './categories.md'
functions:
  categories: './categories.md'

toggleCategory()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]toggleCategory() adds category to icon.

Categories are used to filter icons when displayng icon set.

Usage

Function has the following parameter:

Function returns true on success, false on failure.

Example

src: libraries/tools/icon-set/list-category.ts
title: 'example.ts'
Libraries

toggle-character

title: Assign character to icon in icon set
types:
  IconSet: './index.md'
  IconifyJSON: '/docs/types/iconify-json.md'
functions:
  chars: './chars.md'
  entries: './entries.md'

toggleCharacter()

This function is part of [type]IconSet class in Iconify Tools.

Function [func]toggleCharacter() adds character to icon or removes it.

Usage

Function has the following parameters:

Function returns true on success, false on failure.

Character map

What is the purpose of characters map?

It is used to generate icon fonts. Each icon in an icon font has a character assigned to it. Even when using ligatures, ligatures point to a character, so character is needed.

How to find all characters? {#chars}

You can get list of all assigned characters by using [func]chars() method.

If you want to know characters assigned to an icon, use code like this:

const item = iconSet.entries['some-icon'];
// Set<string>
console.log(item.chars);

It is safe to modify characters directly in [func]entries property.

Example

src: libraries/tools/icon-set/chars.ts
title: 'chars-example.ts'
Libraries

directory

title: Importing SVG from directory
types:
  SVG: '../svg/index.md'
  IconSet: '../icon-set/index.md'
functions:
  cleanupSVG: '../icon/cleanup.md'
  parseColors: '../icon/colors.md'
  runSVGO: '../icon/svgo.md'

Importing SVG from directory

This function is part of import functions in Iconify Tools.

Functions [func]importDirectory() and [func]importDirectorySync() find and import all SVG files from a directory.

Both functions are identical, the only difference is in how they read files. Function [func]importDirectorySync() reads files synchronously, [func]importDirectory() reads files asynchronously.

Functions create [type]IconSet instance, which can be exported to various formats.

Usage

Function has the following parameters:

Function returns [type]IconSet instance.

Options

The [prop]options object has the following optional properties:

Keyword callback can be asynchronous in [func]importDirectory(), but must be synchronous in [func]importDirectorySync(). It has 3 parameters: file name, default generated keyword, icon set. It should return [type]string with keyword or [type]undefined if file should be skipped.

Validation

After importing icons, they need to be:

See example below.

Examples

Asynchronous example:

src: libraries/tools/import/dir.ts
title: 'example.ts'

Synchronous example:

src: libraries/tools/import/dir-sync.ts
title: 'example.ts'
Libraries

index

title: Importing icons
types:
  IconSet: '../icon-set/index.md'
  SVG: '../svg/index.md'
  IconifyJSON: '/docs/types/iconify-json.md'
functions:
  forEach: '../icon-set/for-each.md'
  cleanupSVG: '../icon/cleanup.md'
  runSVGO: '../icon/svgo.md'
  parseColors: '../icon/colors.md'
  deOptimisePaths: '../icon/paths.md'
  importDirectory: './directory.md'
  importDirectorySync: './directory.md'
  importFromFigma: './figma/index.md'

Importing icons

Iconify Tools can import icons from several sources.

Usage

All functions listed below are asynchronous. Most functions create [type]IconSet instances.

Before using Iconify Tools, you should be aware that package is opinionated. Certain SVG elements are not allowed and will cause import to fail. See SVG import limitations.

Async

Most functions are asynchronous.

include libraries/tools/async

Cleanup

After importing icons, make sure you validate them. See [func]cleanupSVG() function.

Import functions

There are several functions for importing icons:

importDirectory()

Functions [func]importDirectory() and [func]importDirectorySync() import SVG files from directory.

importFromFigma()

Function [func]importFromFigma() imports icons from Figma document.

Importing single icon {#svg}

Making a function for importing a single file is redundant. All you have to do is read file and create [type]SVG instance.

See importing SVG documentation.

Importing Iconify icon set {#json}

Making a function for importing [type]IconifyJSON data is also redundant. All you have to do is read file and create [type]IconSet instance.

See importing Iconify icon set documentation.

Libraries

json

title: Importing Iconify Icon Set
types:
  SVG: '../svg/index.md'
  IconSet: '../icon-set/index.md'
  IconifyJSON: '/docs/types/iconify-json.md'

Importing Iconify icon set

This tutorial is part of import functions documentation in Iconify Tools.

There is no special function for importing an icon set because it is redundant. All you have to do is read content from file, parse JSON data and create new [type]IconSet instance.

Example

src: libraries/tools/import/json-min.ts
title: 'example.ts'
Libraries

svg

title: Importing SVG
types:
  SVG: '../svg/index.md'
  IconSet: '../icon-set/index.md'

Importing SVG

This tutorial is part of import functions documentation in Iconify Tools.

There is no special function for importing one icon because it is redundant. All you have to do is read content and create new [type]SVG instance:

Example

src: libraries/tools/import/svg.ts
title: 'example.ts'
Libraries

file-id

title: 'Importing SVG from Figma: Getting file ID'
functions:
  importFromFigma: ./index.md

How to get Figma document ID

This article is part of [func]importFromFigma() documentation.

How to get Figma file ID:

  1. Open file in Figma.
  2. Click the "Share" button in the top right corner.
  3. Click "Copy link".

How to get file ID in Figma

In your clipboard you will have a link to Figma file, which looks like this:

https://www.figma.com/file/9lvc7JGhqpNnpF3OK9kjnG/Quill-Iconset-(Community)?node-id=0%3A1

File ID is between [str]/file/ and next [str]/. In example above, file ID is [str]9lvc7JGhqpNnpF3OK9kjnG.

Community files

Community files contain [str]/community/ in the file link:

https://www.figma.com/community/file/1034432054377533052/Quill-Iconset

It cannot be used to get file ID.

You need to get ID from actual file. If someone else published file to community, you need to clone it, then follow steps above to get file ID.

Libraries

index

title: Importing icons from Figma
types:
  SVG: '../../svg/index.md'
  IconSet: '../../icon-set/index.md'
  IconifyJSON: '/docs/types/iconify-json.md'
  FigmaImportResult: './types.md#result'
  FigmaIconNode: './types.md#icon-node'
  FigmaImportNodeData: './types.md#import-node-data'
  FigmaParentNodeData: './types.md#parent-node-data'
functions:
  cleanupSVG: '../../icon/cleanup.md'
  parseColors: '../../icon/colors.md'
  runSVGO: '../../icon/svgo.md'

Importing icons from Figma

This function is part of import functions in Iconify Tools.

Function [func]importFromFigma() imports SVG files from a Figma file.

It creates [type]IconSet instance, which can be exported to various formats.

Requirements

To import Figma file, you need to have:

Limitations

Import function has few limitations on Figma document structure:

Icon must be one of the following Figma node types:

Parent layers can only be the following Figma node types:

Icons cannot be:

Icons cannot contain:

Usage

Function has the following parameter:

Function returns:

In case of error, import might throw an exception, which you can catch using [func]try and [func]catch.

Function is asynchronous. That means you need to handle it as [class]Promise instance, usually by adding [js]await before function call.

Options

Options object has many properties, most are not required.

Required options used in all parts of import process are:

Required option used when traversing document:

Required option used when generating icon set:

Other options are split in several groups:

Cache options

These options are for caching data:

If you are expecting to run your script more than once, it is a good idea to cache API responses to avoid retrieving the same data multiple times. Set [prop]cacheDir to a writable directory.

TTL options usually do not need changing from default values. Each SVG has unique link, so if icon changes, it will have new cache file, so TTL for icons can be high.

If you set cache options, also consider setting [prop]ifModifiedSince option to true. This will tell import function to retrieve shallow copy of document from Figma, bypassing cache, then comparing if document in Figma has been updated since last cache. If document has been updated, function will clear cache.

const options = {
	// ... other options here
	cacheDir: 'cache/api',
	ifModifiedSince: true,
};

Options for retrieving Figma document

These options are used when retrieving document:

ifModifiedSince

Option [prop]ifModifiedSince is used when you want to retrieve data only if icon set has been updated.

Value can be one of the following:

If Figma document has not been modified, function will return string [str]not_modified.

If option is not set, function cannot return [str]not_modified.

Options for finding icons in Figma document

Function cannot reliably detect which element is an icon and which is not.

These options tell function where to look for icons:

depth

Option [prop]depth tells function how deep it should scan Figma document. Scanning large documents results in slow parsing, so it is recommended to set this option.

Value is number of layers to reach icons.

For example, if icons are placed directly on page without parent group, depth value is [num]2.

Figma tree depth: 2

If icons are placed using the following tree:

Then depth value is [num]3.

Figma tree depth: 3

pages

Option [prop]pages tells function which pages of Figma document contain icons. Value is list of page titles.

Example:

const options = {
	// ... other options here
	pages: ['Icons'],
};

If you set option [prop]pages, option [prop]filterParentNode is ignored.

filterParentNode

Option [prop]filterParentNode is a callback function that filters potential parent nodes.

If possible, it should be used to filter parent nodes, otherwise parser might unexpectedly find and export nodes that match icon, but are on wrong page, that you forgot about.

It is an alternative to [prop]pages option. This option is ignored if [prop]pages option is set.

Callback has the following parameters:

Callback should return:

Callback can be asynchronous.

Example:

const options = {
	// ... other options here

	// 3 levels: page 'Icons' -> frame 'Regular -> icon
	depth: 3,

	// Import icons only from 'Icons' -> 'Regular'
	filterParentNode: (nodes) => {
		switch (nodes.length) {
			case 1: {
				// Page: 'Icons'
				const node = nodes[0];
				return node.name === 'Icons';
			}

			case 2: {
				// Frame: 'Regular'
				const node = nodes[1];
				return node.name === 'Regular';
			}
		}
		return false;
	},
};

iconNameForNode

Option [prop]iconNameForNode is a callback that checks if node is an icon.

Function should return:

Callback parameters are:

Example of callback:

const options = {
	// ... other options here
	iconNameForNode: (node) => {
		if (
			// Icons are stored after 2 parents: page -> container frame -> icon
			node.parents.length !== 2 ||
			// Icons use frames
			node.type !== 'FRAME' ||
			// Icon should be 32x32
			node.width !== 32 ||
			node.height !== 32
		) {
			return null;
		}

		// Return node name as keyword for icon
		return node.name;
	},
};

Callback can be asynchronous.

Options for generating SVG

These options are identical to export settings when you export SVG from Figma:

Options for importing icons

Function imports icons to [type]IconSet instance. These options are for customising import:

Callback functions are identical, the only difference is one is called before importing icon, another one is used after importing icons.

Callbacks have the following parameters:

Callbacks don't need to return anything.

Callbacks can be asynchronous.

Example

The following example imports simple icon set from Figma, where all icons have color [str]#2e4454, then replaces color with [str]currentColor.

src: libraries/tools/import/figma-quill.ts
title: 'example.ts'
Libraries

token

title: 'Importing SVG from Figma: Getting access token'
functions:
  importFromFigma: ./index.md

How to get Figma API access token

This article is part of [func]importFromFigma() documentation.

How to get Figma API access token:

  1. Open Figma.
  2. Select "Home" button in top left corner if you are not on home page.
  3. Click your name in top right corner to see account menu.
  4. Select "Settings".
  5. In settings window click "Account".
  6. Scroll to "Personal access tokens", in token name type something then hit enter key.

You should see new token. Copy it.

If you at some point would want to remove token, follow steps above. Below form to generate new tokens, you'll see list of all tokens. From there you can remove tokens.

Never commit token to a repository or publish it anywhere! Keep it secret. There are many ways to keep token secret, most common is using environmental variables to pass token to script. There are plenty of tutorials available that explain different methods.

Libraries

types

title: 'Importing SVG from Figma: Types'
types:
  IconSet: '../../icon-set/index.md'
  FigmaImportResult: './types.md#result'
  FigmaIconNode: './types.md#icon-node'
  FigmaImportNodeData: './types.md#import-node-data'
  FigmaParentNodeData: './types.md#parent-node-data'
functions:
  importFromFigma: ./index.md

Types used in importFromFigma()

This article is part of [func]importFromFigma() documentation.

FigmaImportResult {#result}

On success, [func]importFromFigma() returns [type]FigmaImportResult object, which has the following properties:

FigmaIconNode {#icon-node}

Type [type]FigmaIconNode is used in callback and in [prop]missing property of [type]FigmaImportResult.

It represents one icon and has the following properties:

On various stages of parsing icons, the following properties are added to object:

FigmaImportNodeData {#import-node-data}

Type [type]FigmaImportNodeData is used in first parameter for [prop]iconNameForNode callback.

It is a simple object with the following properties:

Example of node data passed to callback:

{
	"id": "12:724",
	"type": "FRAME",
	"name": "arrow-down",
	"width": 32,
	"height": 32,
	"parents": [
		{ "id": "0:1", "type": "CANVAS", "name": "Icons" },
		{ "id": "12:479", "type": "FRAME", "name": "Regular" }
	]
}

FigmaParentNodeData {#parent-node-data}

Type [type]FigmaParentNodeData is used in [type]FigmaImportNodeData and in first parameter for [prop]filterParentNode callback.

It is a simple object with the following properties:

Examples:

{
	"id": "0:1",
	"type": "CANVAS",
	"name": "Icons"
}
{
	"id": "12:479",
	"type": "FRAME",
	"name": "Regular"
}
Libraries

api-query

title: Sending API Query
functions:
  importFromFigma: '../import/figma/index.md'
  downloadGitHubRepo: './github.md'
  downloadFile: './download-file.md'

Sending API query

This tutorial is part of package functions documentation in Iconify Tools.

Function [func]sendAPIQuery() is a wrapper for [func]fetch with caching.

It is used by functions that retrieve text data from remote sources, such as [func]importFromFigma() and [func]downloadGitHubRepo().

To retrieve binary files, see [func]downloadFile().

Usage

Function has the following parameters:

Function returns:

Function is asynchronous. That means you need to handle it as [class]Promise instance, usually by adding [js]await before function call.

APIQueryParams

[type]APIQueryParams object has the following properties:

Example:

const params = {
	uri: 'https://api.whatever.com/some-file/',
	params: new URLSearchParams({
		version: '123',
	}),
	headers: {
		Accept: 'application/json',
	},
};

APICacheOptions

[type]APICacheOptions object has the following properties:

Cache management

If [prop]cache property is not set, data is not cached.

If [prop]cache property is set, function will generate unique hash for query, will check if file with that hash already exists, if it has not expired. On success it will return cached data instead of fetching new data.

You can purge cache at any time using [func]clearAPICache() function:

import { clearAPICache } from '@iconify/tools/lib/download/api/cache';

const cacheDir = 'cache';

// Asynchronous function, so wrapping it in anonymous async function.
// Not needed for Node 17+ that supports top level await.
(async () => {
	await clearAPICache(cacheDir);
})();

Example

src: libraries/tools/package/api.ts
title: 'example.ts'
Libraries

bump-version

title: Increasing version number

Increasing version number

This tutorial is part of package functions documentation in Iconify Tools.

Function [func]bumpVersion() is a simple function that increases version number.

It can be used to automatically increase version number when updating existing package.

Usage

Function has the following parameter:

Function returns updated version number.

Example

src: libraries/tools/package/version.ts
title: 'example.ts'
Libraries

compare

title: Comparing directories

Comparing directories

This tutorial is part of package functions documentation in Iconify Tools.

Function [func]compareDirectories() compares contents of two directories.

It is used to check if package generated by one of export functions and package downloaded from elsewhere, such as NPM package are identical. If packages are identical, there is no need to publish a new version.

Usage

Function has the following parameters:

Function returns:

Function is asynchronous. That means you need to handle it as [class]Promise instance, usually by adding [js]await before function call.

Options

Options object has the following optional properties:

Libraries

download-file

title: Downloading binary file
functions:
  downloadGitHubRepo: './github.md'
  downloadNPMPackage: './npm.md'
  sendAPIQuery: './api-query.md'

Download binary file

This tutorial is part of package functions documentation in Iconify Tools.

Function [func]downloadFile() is a wrapper for [func]fetch that downloads binary file.

It is used by functions that retrieve archives in download functions, such as [func]downloadGitHubRepo() and [func]downloadNPMPackage().

To retrieve text files, see [func]sendAPIQuery().

Usage

Function has the following parameters:

Function is asynchronous. That means you need to handle it as [class]Promise instance, usually by adding [js]await before function call.

APIQueryParams

[type]APIQueryParams object has the following properties:

Libraries

git-repo-hash

title: Getting Git repository hash
functions:
  downloadGitRepo: './git.md'

Getting Git repository hash

This tutorial is part of package functions documentation in Iconify Tools.

Function [func]getGitRepoHash() retrieves last commit hash from local Git repository.

It is used by [func]downloadGitRepo().

Usage

Function has the following parameter:

Function returns last commit hash as [type]string.

Function is asynchronous.

Libraries

git

title: Downloading Git repository
types:
  DownloadGitRepoResult: './git.md#result'

Downloading Git repository

This tutorial is part of package functions documentation in Iconify Tools.

Function [func]downloadGitRepo() creates a shallow clone of Git repository.

Git executable

This function uses Git to clone repository. Make sure Git is installed on your computer.

Usage

Function has the following parameter:

Function returns:

In case of error, function might throw an exception, which you can catch using [func]try and [func]catch.

Function is asynchronous. That means you need to handle it as [class]Promise instance, usually by adding [js]await before function call.

Options

Options object has the following mandatory properties:

and the following optional properties:

ifModifiedSince

Option [prop]ifModifiedSince is used when you want to retrieve data only if repository has been updated.

Value can be one of the following:

If repository has not been modified, function will return string [str]not_modified.

If option is not set, function cannot return [str]not_modified.

Result

Result object has the following properties:

Example

src: libraries/tools/package/git.ts
title: 'boxicons.ts'
Libraries

github-commit

title: Getting last commit hash for GitHub repository
functions:
  downloadGitHubRepo: './github.md'

Getting last commit hash for GitHub repository

This tutorial is part of package functions documentation in Iconify Tools.

Function [func]getGitHubRepoHash() retrieves last commit hash from remote GitHub repository using GitHub API.

It is used by [func]downloadGitHubRepo() to check if repository has been updated and to generate download link for archive.

Usage

Function has the following parameter:

Function returns last commit hash as [type]string.

Function is asynchronous.

Libraries

github

title: Downloading GitHub repository using API
types:
  DownloadGitHubRepoResult: './github.md#result'

Downloading GitHub repository using API

This tutorial is part of package functions documentation in Iconify Tools.

Function [func]downloadGitHubRepo() downloads files from GitHub repository using GitHub API.

Usage

Function has the following parameter:

Function returns:

In case of error, function might throw an exception, which you can catch using [func]try and [func]catch.

Function is asynchronous. That means you need to handle it as [class]Promise instance, usually by adding [js]await before function call.

Options

Options object has the following mandatory properties:

and the following optional properties:

Function downloads archive, puts it in [prop]target directory, then unpacks it in sub-directory. There are two optional properties that allow you remove outdated files without removing everything. Options do not work if [prop]cleanup is enabled because [prop]cleanup removes everything.

token

You can get GitHub API token from developer settings on GitHub.

Token does not need write or admin access, access to workflows, it requires only read access to repository you want to clone.

If you are accessing public repositories, checking [str]repo:status and [str]public_repo is enough.

If you are accessing private repositories, check [str]repo section.

Never commit token to a repository or publish it anywhere! Keep it secret. There are many ways to keep token secret, most common is using environmental variables to pass token to script. There are plenty of tutorials available that explain different methods.

ifModifiedSince

Option [prop]ifModifiedSince is used when you want to retrieve data only if repository has been updated.

Value can be one of the following:

If repository has not been modified, function will return string [str]not_modified.

If option is not set, function cannot return [str]not_modified.

Result

Result object has the following properties:

Value is [prop]contentsDir always contains [prop]rootDir because archives are unpacked in sub-directory of [prop]rootDir. For example:

{
	"downloadType": "github",
	"rootDir": "output/github-test",
	"contentsDir": "output/github-test/iconify-collections-json-4049946",
	"hash": "40499460e21011478a64c1cb1212f3308168462c"
}

Example

src: libraries/tools/package/github.ts
title: 'download-jam-icons.ts'
Libraries

gitlab-commit

title: Getting last commit hash for GitLab repository
functions:
  downloadGitLabRepo: './gitlab.md'

Getting last commit hash for GitLab repository

This tutorial is part of package functions documentation in Iconify Tools.

Function [func]getGitLabRepoHash() retrieves last commit hash from remote GitLab repository using GitLab API.

It is used by [func]downloadGitLabRepo() to check if repository has been updated and to generate download link for archive.

Usage

Function has the following parameter:

Function returns last commit hash as [type]string.

Function is asynchronous.

Libraries

gitlab

title: Downloading GitLab repository using API
types:
  DownloadGitLabRepoResult: './gitlab.md#result'

Downloading GitLab repository using API

This tutorial is part of package functions documentation in Iconify Tools.

Function [func]downloadGitLabRepo() downloads files from GitLab repository using GitLab API.

Usage

Function has the following parameter:

Function returns:

In case of error, function might throw an exception, which you can catch using [func]try and [func]catch.

Function is asynchronous. That means you need to handle it as [class]Promise instance, usually by adding [js]await before function call.

Options

Options object has the following mandatory properties:

and the following optional properties:

Function downloads archive, puts it in [prop]target directory, then unpacks it in sub-directory. There are two optional properties that allow you remove outdated files without removing everything. Options do not work if [prop]cleanup is enabled because [prop]cleanup removes everything.

token

You can get GitLab API token from access tokens page on GitLab.

If you are creating a new token, set scope to [str]read_api.

Never commit token to a repository or publish it anywhere! Keep it secret. There are many ways to keep token secret, most common is using environmental variables to pass token to script. There are plenty of tutorials available that explain different methods.

ifModifiedSince

Option [prop]ifModifiedSince is used when you want to retrieve data only if repository has been updated.

Value can be one of the following:

If repository has not been modified, function will return string [str]not_modified.

If option is not set, function cannot return [str]not_modified.

Result

Result object has the following properties:

Value is [prop]contentsDir always contains [prop]rootDir because archives are unpacked in sub-directory of [prop]rootDir. For example:

{
	"downloadType": "gitlab",
	"rootDir": "output/gitlab-test",
	"contentsDir": "output/gitlab-test/iconify-collections-json-4049946",
	"hash": "40499460e21011478a64c1cb1212f3308168462c"
}

Example

src: libraries/tools/package/gitlab.ts
title: 'download-jam-icons.ts'
Libraries

index

title: Managing packages
types:
  IconSet: '../icon-set/index.md'
  IconifyJSON: '/docs/types/iconify-json.md'
functions:
  importDirectory: '../import/directory.md'
  importFromFigma: '../import/figma/index.md'
  downloadGitRepo: './git.md'
  downloadGitHubRepo: './github.md'
  downloadGitLabRepo: './gitlab.md'
  downloadNPMPackage: './npm.md'
  compareDirectories: './compare.md'
  sendAPIQuery: './api-query.md'
  downloadFile: './download-file.md'
  bumpVersion: './bump-version.md'
  getPackageVersion: './package-version.md'
  getNPMVersion: './npm-version.md'
  getGitRepoHash: './git-repo-hash.md'
  getGitHubRepoHash: './github-commit.md'
  getGitLabRepoHash: './gitlab-commit.md'

Managing packages

Iconify Tools has several functions to help automate downloading, comparing and updating packages.

Async

Most functions listed below are asynchronous.

include libraries/tools/async

Downloading packages

These functions download packages from various sources.

Functions can be used to download source for icon sets, which can be imported using [func]importDirectory() function.

Functions can also be used to compare exported data with previously published data, then publish new version if package was changed.

Additionally, there are few functions to download files by URL:

Versions {#versions}

When publishing packages, you might want to change package version. Iconify Tools offers several functions to help you automate process:

Functions to get version number or commit hash from local files:

Functions to get version number or commit hash from remote package/repository:

Comparing directories

When automating build process, publishing new package when nothing was changed makes no sense. There is a function in Iconify Tools to check for changes:

Unlike simple comparison, this function ignores version numbers in [file]package.json, hidden files and different line endings.

Libraries

npm-version

title: Getting package version and URL from NPM
functions:
  downloadNPMPackage: './npm.md'
  getNPMVersion: './package-version.md'

Getting NPM package version and URL

This tutorial is part of package functions documentation in Iconify Tools.

Function [func]getNPMVersion() retrieves latest version of package from NPM registry and URL to download package.

Usage

Function has the following parameter:

Function returns [type]object with the following properties:

Example

src: libraries/tools/package/npm-version.ts
title: 'example.ts'
extra:
  - src: libraries/tools/package/npm-version.json
    title: 'Result:'
Libraries

npm

title: Downloading NPM package
types:
  DownloadNPMPackageResult: './npm.md#result'

Downloading NPM package

This tutorial is part of package functions documentation in Iconify Tools.

Function [func]downloadNPMPackage() downloads NPM package.

Unlike [bash]npm install, this function downloads and extracts only requested NPM package, it does not install dependencies and does not run any scripts.

Usage

Function has the following parameter:

Function returns:

In case of error, function might throw an exception, which you can catch using [func]try and [func]catch.

Function is asynchronous. That means you need to handle it as [class]Promise instance, usually by adding [js]await before function call.

Options

Options object has the following mandatory properties:

and the following optional properties:

ifModifiedSince

Option [prop]ifModifiedSince is used when you want to retrieve data only if repository has been updated.

Value can be one of the following:

If package has not been updated, function will return string [str]not_modified.

If option is not set, function cannot return [str]not_modified.

Result

Result object has the following properties:

Value is [prop]contentsDir always contains [prop]rootDir because archives are unpacked in sub-directory of [prop]rootDir. For example:

{
	"downloadType": "npm",
	"rootDir": "output/npm-test",
	"contentsDir": "output/npm-test/package",
	"version": "1.0.1"
}

Example

src: libraries/tools/package/npm.ts
title: 'example.ts'
Libraries

package-version

title: Getting version number of package
functions:
  downloadNPMPackage: './npm.md'
  getNPMVersion: './npm-version.md'

Getting version number of package

This tutorial is part of package functions documentation in Iconify Tools.

Function [func]getPackageVersion() is a simple function that retrieves version number from [file]package.json in target directory.

It is used by [func]downloadNPMPackage() to retrieve version number of package that has already been downloaded and extracted. It can also be used to get version number of package downloaded from Git repository (as shown in example below).

Usage

Function has the following parameter:

Function returns version number as [type]string.

Also see [func]getNPMVersion().

Function is asynchronous.

Example

src: libraries/tools/package/package-version.ts
title: 'example.ts'
Libraries

index

title: SVG Class
types:
  IconSet: "../icon-set/index.md"
  IconifyIcon: "/docs/types/iconify-icon.md"
functions:
  cleanupSVG: "../icon/cleanup.md"
  runSVGO: "../icon/svgo.md"

SVG class

[type]SVG class represents one icon. It is used in Iconify Tools in functions for icon content.

Usage

To create an instance, use this code:

import { SVG } from "@iconify/tools";

const svg = new SVG(
  '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M7 6v12l10-6z" fill="currentColor"/></svg>'
);

If you are working with icon sets, use function [func]toSVG() of [type]IconSet instance to get [type]SVG instance:

const svg = iconSet("home");
if (!svg) {
  throw new Error('Icon "home" is not available or invalid');
}

Properties

[type]SVG instance has several properties, all are initialized when instance is created:

Methods

The following methods are available:

Validating and cleaning up icon

Unfortunately, many editors leave lots of junk in SVG files, sometimes multiplying icon file size several times.

SVG files might also contain scripts and links to external resources.

This is why after loading icon, it should be validated and cleaned up. See [func]cleanupSVG() function.

Optimising icon

The cleanup process is very basic, it does bare minimum to get rid of bad stuff. However, icons often contain unnecessary or unused elements and attributes.

Before exporting icons, you need to properly fix them. The process can include:

See icon manipulation functions.

Libraries

build-parsed-svg

title: buildParsedSVG() in Iconify Utils
types:
  IconifyIcon: '/docs/types/iconify-icon.md'
  SVGViewBox: './get-svg-viewbox.md'
functions:
  parseSVGContent: './parse-svg-content.md'
  convertParsedSVG: './convert-parsed-svg.md'
  iconToHTML: './icon-to-html.md'

buildParsedSVG()

This function is part of Iconify Utils package.

Function [func]buildParsedSVG() parses result of [func]parseSVGContent().

It validates and cleans up [tag]svg attributes, extracts and validates [prop]viewBox and returns data as a list of attributes for [tag]svg element and content.

Result can be used by functions like [func]iconToHTML() to generate SVG or to generate various components.

Usage

This function has the following parameter:

This function returns data with type [type]ParsedSVGContent, [type]undefined on error. See below.

Result {#build-result}

The result is an object with the following properties:

List of attributes in the result does not include [prop]xmlns because it is identical in all SVG. It always includes [prop]viewBox, usually includes [prop]width and [prop]height.

You can use [func]iconToHTML() to convert the result to string.

Example

Example using [func]parseSVGContent() with [func]buildParsedSVG() and [func]iconToHTML() to clean up icon:

src: libraries/utils/build-parsed-svg.ts
title: 'cleanup.ts'
Libraries

calculate-size

title: calculateSize() in Iconify Utils
functions:
  iconToSVG: './icon-to-svg.md'

calculateSize()

This function is part of Iconify Utils package.

Function [func]calculateSize() is used for calculating icon's [prop]width or [prop]height when only one property is provided.

For example, if you have icon with [attr]viewBox="0 0 36 24" and [prop]height is set to [str]1em, this function is used to calculate [prop]width property, which will be [str]1.5em.

Function is used by [func]iconToSVG() to generate attributes. It can also be used by things like icon pickers, where you can show hint for [prop]width value when user inputs [prop]height value.

Usage

Function has the following parameters:

Function returns calculated size.

Example

src: libraries/utils/calculate-size.ts
title: 'examples.ts'
extra:
  - src: libraries/utils/calculate-size.txt
    title: 'Result:'
Libraries

clean-up-inner-html

title: cleanUpInnerHTML() in Iconify Utils

cleanUpInnerHTML()

This function is part of Iconify Utils package.

Function allows assigning a string to [prop]innerHTML property of a DOM element in documents that use strict security policy [str]require-trusted-types-for 'script';.

This is a very basic function; it does not do any actual content clean up or validation.

It is designed to be used with Iconify icon components that render SVG, which has already been validated and cleaned up.

Usage

Instead of this:

node.innerHTML = '<p>Test</p>';

use this:

import { cleanUpInnerHTML } from '@iconify/utils/lib/svg/inner-html';

node.innerHTML = cleanUpInnerHTML('<p>Test</p>');

If a browser supports security policy, it will return a cleaned-up string, without actually modifying anything.

If a browser does not support security policy, it will return string as is.

This is a simple workaround for an absolutely useless security policy.

About require-trusted-types-for security policy

Security policy requires libraries to clean up HTML before assigning it to [prop]innerHTML property of a DOM element.

To add that policy to your document, all you have to do is add the following code to page header:

<meta
  http-equiv="Content-Security-Policy"
  content="require-trusted-types-for 'script';"
/>

However, be aware that policy does not provide any actual security and is pretty much useless!

The process of cleaning up HTML is not regulated in any way, it is up to a library to decide how to clean up HTML. This means libraries can just emulate clean up without doing any actual clean up. And that is exactly what this function does.

Your website security should not rely on such useless "security" policies.

Libraries

color-to-string

title: colorToString() in Iconify Utils
types:
  Color: './color.md'
functions:
  stringToColor: './string-to-color.md'

colorToString()

This function is part of Iconify Utils package.

Function [func]colorToString() convert [type]Color objects to [type]string.

It is the opposite of [func]stringToColor().

Converting color from string using [func]stringToColor(), then back to string using this function can be used to validate and clean up color strings.

Usage

Function has one parameter:

Function returns [type]string.

Example

src: libraries/utils/color-to-string.ts
title: 'demo.ts'
Libraries

color

title: Color Type

Color type

[type]Color type is used in Iconify Utils in functions for parsing colors.

You can find this type in [file]src/colors/types.ts of Iconify Utils source code.

Type is an object, with [prop]type property showing what color type it is, then optional properties for that type.

Browsers support various complex colors, which can contain CSS variables, functions. Iconify Utils parser is very basic, it supports only commonly used namespaces that have been supported by all browsers for many years.

RGB

RGB color, usually converted from hexadecimal color like [str]#ff8080, color keyword [str]red or RGBA color like [str]rgba(255, 128, 128, 0.5).

It has the following properties:

HSL

HSL color, usually converted from HSL or HSLA color like [str]hsla(90, 50%, 50%, 0.5).

It has the following properties:

LAB

Lab color, currently being implemented by browsers, is converted from color strings like [str]lab(50% 50 50 / 1).

It has the following properties:

LCH

LCH color, currently being implemented by browsers, is converted from color strings like [str]lch(50% 50 50 / 1).

It has the following properties:

Keywords

Several keywords have their own types that represent special colors.

They exist because functions for parsing colors can be used for cleaning up and parsing various icons, where finding values like [str]currentColor and [str]none could be important.

transparent

Transparent color has a special type with only one property:

When converting transparent colors like [str]rgba(0, 0, 0, 0), conversion function will return [prop]transparent type, making it easier to compare various colors.

none

[str]none also has a special type with only one property:

currentColor

[str]currentColor also has a special type with only one property:

Other colors

This type is meant for parsing basic colors in SVG, not full color parsing, so it is limited only to simple colors and keywords that are important when parsing icons.

Libraries

compare-colors

title: compareColors() in Iconify Utils
types:
  Color: './color.md'

compareColors()

This function is part of Iconify Utils package.

Function [func]compareColors() compares two [type]Color objects, returning true if colors are identical.

This function can be used to parse colors in SVG. When the same color is represented with different methods, this function can help find duplicate colors.

Usage

Function has two parameters:

Function returns true if colors are identical, false if not.

Example

src: libraries/utils/compare-colors.ts
title: 'demo.ts'
Libraries

convert-info

title: convertIconSetInfo() in Iconify Utils
types:
  IconifyInfo: '/docs/types/iconify-info.md'

convertIconSetInfo()

This function is part of Iconify Utils package.

Function [func]convertIconSetInfo() converts and validates icon set information.

Some old icon sets might have information in legacy format, which was created before Iconify projects moved to TypeScript. This function will accept both old and new formats, will convert and validate it and will return correct [type]IconifyInfo data.

Usage

Function has the following parameters:

Function returns:

Example

src: libraries/utils/convert-info.ts
title: 'usage.ts'
extra:
  - src: libraries/utils/convert-info.json
    title: 'Result:'
Libraries

convert-parsed-svg

title: convertParsedSVG() in Iconify Utils
types:
  IconifyIcon: '/docs/types/iconify-icon.md'
  SVGViewBox: './get-svg-viewbox.md'
functions:
  parseSVGContent: './parse-svg-content.md'
  buildParsedSVG: './build-parsed-svg.md'
  iconToHTML: './icon-to-html.md'

convertParsedSVG()

This function is part of Iconify Utils package.

Function [func]convertParsedSVG() converts result of [func]parseSVGContent() to [type]IconifyIcon.

Function also does basic validation and cleanup of [tag]svg attributes.

Result can be used by various functions and icon components that use [type]IconifyIcon type.

Usage

This function has the following parameter:

This function returns data with type [type]IconifyIcon, [type]undefined on error.

Iconify Tools

This function is very basic. For advanced parsing and clean up, use Iconify Tools.

Example

Example using [func]parseSVGContent() with [func]convertParsedSVG() to get icon data in [type]IconifyIcon format, which can be used by various icon components:

src: libraries/utils/convert-parsed-svg.ts
title: 'convert.ts'
Libraries

default-icon-customisations

title: defaultIconCustomisations in Iconify Utils
types:
  FullIconifyIconCustomisations: './icon-customisations.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
  FullIconifyIcon: './full-iconify-icon.md'
functions:
  iconToSVG: './icon-to-svg.md'
  mergeCustomisations: './merge-customisations.md'

defaultIconCustomisations

This constant is part of Iconify Utils package.

Constant [func]defaultIconCustomisations is used for default [type]FullIconifyIconCustomisations values.

It is merged from 2 parts:

defaultIconSizeCustomisations

Constant [func]defaultIconSizeCustomisations represents size customisations: [prop]width and [prop]height:

const defaultIconSizeCustomisations = {
	width: null,
	height: null,
};

defaultIconTransformations

Constant [func]defaultIconTransformations represents transformations:

const defaultIconTransformations = {
	rotate: 0,
	vFlip: false,
	hFlip: false,
};

Default values for transformations are shared with [type]IconifyIcon type.

Usage

src: libraries/utils/default-icon-customisations.ts
title: 'example.ts'

Usually it is used with [func]mergeCustomisations() function.

It is also used in functions that require only partial customisations, such as [func]iconToSVG(), but internally actually uses full customisations.

Libraries

default-icon-props

title: defaultIconProps in Iconify Utils
types:
  IconifyIcon: '/docs/types/iconify-icon.md'
  IconifyOptional: '/docs/types/iconify-icon.md#iconify-optional'
  FullIconifyIcon: './full-iconify-icon.md'
functions:
  iconToSVG: './icon-to-svg.md'

defaultIconProps

This constant is part of Iconify Utils package.

Constant [func]defaultIconProps contains default values for optional [type]IconifyIcon properties.

It is merged from 2 parts:

defaultIconDimensions

Constant [func]defaultIconDimensions contains default values for icon dimensions:

const defaultIconDimensions = {
	left: 0,
	top: 0,
	width: 16,
	height: 16,
};

defaultIconTransformations

Constant [func]defaultIconTransformations contains default values for icon transformations:

const defaultIconTransformations = {
	rotate: 0,
	vFlip: false,
	hFlip: false,
};

Usage

Function has the following parameter:

Function returns full icon data with type [type]FullIconifyIcon.

Example

src: libraries/utils/default-icon-props.ts
title: 'usage.ts'
extra:
  - src: libraries/utils/default-icon-props.json
    title: 'Result:'

It is used in functions that require only partial icon data, such as [func]iconToSVG(), but internally actually use full icon.

Libraries

expand-icon-set

title: expandIconSet() in Iconify Utils
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
  IconifyOptional: '/docs/types/iconify-icon.md#iconify-optional'
  FullIconifyIcon: './full-iconify-icon.md'
functions:
  minifyIconSet: './minify-icon-set.md'

expandIconSet()

This function is part of Iconify Utils package.

Function [func]expandIconSet() de-optimises icon set, opposite of [func]minifyIconSet().

Usage

Function has only one parameter:

Function does not create a new object, it de-optimises object passed to function.

What exactly does it do? {#explanation}

See [func]minifyIconSet() for details.

Example

src: libraries/utils/expand.ts
title: 'usage.ts'
extra:
  - src: libraries/utils/expand.json
    title: 'Result:'
Libraries

flip-from-string

title: flipFromString() in Iconify Utils
types:
  IconCustomisations: './icon-customisations.md'

flipFromString()

This function is part of Iconify Utils package.

Function [func]flipFromString() applies [prop]flip shorthand property to [type]IconCustomisations object.

Usage

Function has the following parameters:

Function does not return anything, it applies changes to object passed in first parameter.

Value

Value can be set of the following strings, separated by space and/or comma:

Example

src: libraries/utils/flip-from-string.ts
title: 'demo.ts'
Libraries

full-iconify-icon

title: FullIconifyIcon Type
types:
  IconifyIcon: '/docs/types/iconify-icon.md'
functions:
  defaultIconProps: './default-icon-props.md'

FullIconifyIcon type

[type]FullIconifyIcon type is used in Iconify Utils to handle icon data.

You can find this type in [file]src/icon/index.ts of Iconify Utils source code.

This type is identical to [type]IconifyIcon, except that all properties are mandatory.

import type { IconifyIcon } from '@iconify/types';

export type FullIconifyIcon = Required<IconifyIcon>;

See [type]IconifyIcon type for details.

Example

{
	"body": "<path d=\"M7 6v12l10-6z\" fill=\"currentColor\"/>",
	"left": 0,
	"top": 0,
	"width": 24,
	"height": 24,
	"rotate": 0,
	"vFlip": false,
	"hFlip": false
}

Usage

To convert [type]IconifyIcon to [type]FullIconifyIcon, merge [func]defaultIconProps with your data:

src: libraries/utils/full-iconify-icon.ts
title: 'usage.ts'
extra:
  - src: libraries/utils/full-iconify-icon.json
    title: 'Result:'
Libraries

get-icon-content-css

title: getIconContentCSS() in Iconify Utils
functions:
  getIconsContentCSS: './get-icons-content-css.md'
  getIconCSS: './get-icon-css.md'
types:
  IconifyIcon: '/docs/types/iconify-icon.md'

getIconContentCSS()

This function is part of Iconify Utils package.

Function [func]getIconContentCSS() generates stylesheet to render an icon as content of pseudo-element.

It generates code only for one icon. To generate code for multiple icons at the same time, see [func]getIconsContentCSS().

If, instead of using icon as content of a pseudo-element, you want to use icon as a background or mask image, see [func]getIconCSS().

To use icon in HTML, all you need to do is create any element, such as [tag]span with class name that you passed in [prop]iconSelector option.

Color and size

When using icon as content of pseudo-element, [prop]currentColor cannot be used, so icon must have a hardcoded color.

Icon also must have fixed dimensions, which cannot be changed in CSS.

If you want to use an icon with [prop]currentColor in CSS or want to resize icon using CSS, you should use [func]getIconCSS() instead.

Usage

Function has the following parameters:

Function returns [type]string with stylesheet for icon.

Options

The [prop]options object has the following properties:

Result

Example of generated stylesheet:

.icon::after {
	content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cpath fill='black' d='M10 20v-6h4v6h5v-8h3L12 3L2 12h3v8h5Z'/%3E%3C/svg%3E");
}

That code can be used in HTML with any element, such as [tag]span with class name that you passed in [prop]iconSelector option:

<span class="icon"></span>

Color option

include: libraries/utils/css-color-content

Example

src: libraries/utils/get-icon-content-css.ts
title: 'generate-css.ts'
extra:
  - src: libraries/utils/get-icon-content-css.css
    title: 'Result:'
  - src: libraries/utils/get-icon-content-css.html
    title: 'Usage in HTML:'
Libraries

get-icon-css

title: getIconCSS() in Iconify Utils
functions:
  getIconsCSS: './get-icons-css.md'
  getIconContentCSS: './get-icon-content-css.md'
types:
  IconifyIcon: '/docs/types/iconify-icon.md'

getIconCSS()

This function is part of Iconify Utils package.

Function [func]getIconCSS() generates stylesheet to render an icon as a background or mask image.

It generates code only for one icon. To generate code for multiple icons at the same time, see [func]getIconsCSS().

If instead of using icon as a background or mask image, you want to use icon as content of a pseudo-element, see [func]getIconContentCSS().

To use icon in HTML, all you need to do is create any element, such as [tag]span with class name that you passed in [prop]iconSelector option.

Color

Monotone icons are rendered as mask image with background color set to [prop]currentColor. That means icon will use same color as text.

To change icon color, simply change text color.

include: common/css-demo

Icons with palette are rendered as background image.

You can also use [prop]color option to convert monotone icon to icon with palette. See [str]Color option section below.

Usage

Function has the following parameters:

Function returns [type]string with stylesheet for icon.

Options

The [prop]options object has the following properties:

Result

Example of generated stylesheet:

.icon {
	display: inline-block;
	width: 1em;
	height: 1em;
	background-color: currentColor;
	-webkit-mask: no-repeat center / 100%;
	mask: no-repeat center / 100%;
	-webkit-mask-image: var(--svg);
	mask-image: var(--svg);
	--svg: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cpath fill='black' d='M10 20v-6h4v6h5v-8h3L12 3L2 12h3v8h5Z'/%3E%3C/svg%3E");
}

That code can be used in HTML with any element, such as [tag]span with class name that you passed in [prop]iconSelector option:

<span class="icon"></span>

Color option

include: libraries/utils/css-color
<span class="icon" style="color: var(--icon-color)"></span>

Examples

Generating CSS for a monotone icon:

src: libraries/utils/get-icon-css.ts
title: 'generate-css.ts'
extra:
  - src: libraries/utils/get-icon-css.css
    title: 'Result:'
  - src: libraries/utils/get-icon-css.html
    title: 'Usage in HTML:'

Generating CSS for an icon with palette:

src: libraries/utils/get-icon-css2.ts
title: 'generate-css.ts'
extra:
  - src: libraries/utils/get-icon-css2.css
    title: 'Result:'
  - src: libraries/utils/get-icon-css2.html
    title: 'Usage in HTML:'

Using pseudo-element for icon:

src: libraries/utils/get-icon-css3.ts
title: 'generate-css.ts'
extra:
  - src: libraries/utils/get-icon-css3.css
    title: 'Result:'
  - src: libraries/utils/get-icon-css3.html
    title: 'Usage in HTML:'
Libraries

get-icon-data

title: getIconData() in Iconify Utils
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
functions:
  iconToSVG: './icon-to-svg.md'

getIconData()

This function is part of Iconify Utils package.

Function [func]getIconData() retrieves data for one icon from icon set.

Usage

Function has the following parameters:

Function returns icon data with type [type]IconifyIcon, null on error.

Example

src: libraries/utils/get-icon.ts
title: 'usage.ts'
demo: libraries/utils/get-icon.html
demoFirst: false
demoTitle: 'Result:'
Libraries

get-icons-content-css

title: getIconsContentCSS() in Iconify Utils
functions:
  getIconsCSS: './get-icons-css.md'
  getIconContentCSS: './get-icon-content-css.md'
types:
  IconifyIcon: '/docs/types/iconify-icon.md'
  IconifyJSON: '/docs/types/iconify-json.md'

getIconsCSS()

This function is part of Iconify Utils package.

Function [func]getIconsCSS() generates stylesheet for several icons from an icon set to render them as background or mask images.

It generates code multiple icons from an icon set, splitting common code and icon-specific code. To generate code for one icon without splitting code, see [func]getIconContentCSS().

If, instead of using icons as content of a pseudo-elements, you want to use icons as background or mask images, see [func]getIconsCSS().

To use icons in HTML, all you need to do is create any element, such as [tag]span with class names for an icon set and icon.

Color and size

When using icons as content of pseudo-elements, [prop]currentColor cannot be used, so icons must have a hardcoded color.

Icons also must have fixed dimensions, which cannot be changed in CSS.

If you want to use icons with [prop]currentColor in CSS or want to resize icons using CSS, you should use [func]getIconsCSS() instead.

Usage

Function has the following parameters:

Function returns [type]string with stylesheet for icons.

Options

The [prop]options object has the following properties:

Result

Example of generated stylesheet:

.icon--tabler--code::after {
	content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cpath fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m7 8l-4 4l4 4m10-8l4 4l-4 4M14 4l-4 16'/%3E%3C/svg%3E");
}

.icon--tabler--crystal-ball::after {
	content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cg fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='2'%3E%3Cpath d='M6.73 17.018a8 8 0 1 1 10.54 0'/%3E%3Cpath d='M5 19a2 2 0 0 0 2 2h10a2 2 0 1 0 0-4H7a2 2 0 0 0-2 2zm6-12a3 3 0 0 0-3 3'/%3E%3C/g%3E%3C/svg%3E");
}

.icon--tabler--view-360::after {
	content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cg fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='2'%3E%3Ccircle cx='12' cy='12' r='9'/%3E%3Cellipse cx='12' cy='12' rx='4' ry='9'/%3E%3Cpath d='M3 12c0 2.21 4.03 4 9 4s9-1.79 9-4s-4.03-4-9-4s-9 1.79-9 4z'/%3E%3C/g%3E%3C/svg%3E");
}

That code can be used in HTML with any element, such as [tag]span with class names for both common code and icon specific code:

<span class="icon--tabler--code"></span>

Color option

include: libraries/utils/css-color-content

If you want to use different colors for different icons, you need to call [func]getIconsContentCSS() multiple times with different values for the [prop]color option.

If you want to have several entries of the same monotone icon with different colors, you need to call [func]getIconsContentCSS() multiple times with different values for the [prop]color and [prop]iconSelector options.

Example

src: libraries/utils/get-icons-content-css.ts
title: 'generate-css.ts'
extra:
  - src: libraries/utils/get-icons-content-css.css
    title: 'Result:'
  - src: libraries/utils/get-icons-content-css.html
    title: 'Usage in HTML:'
Libraries

get-icons-css

title: getIconsCSS() in Iconify Utils
functions:
  getIconCSS: './get-icon-css.md'
  getIconsContentCSS: './get-icons-content-css.md'
types:
  IconifyIcon: '/docs/types/iconify-icon.md'
  IconifyJSON: '/docs/types/iconify-json.md'

getIconsCSS()

This function is part of Iconify Utils package.

Function [func]getIconsCSS() generates stylesheet for several icons from an icon set to render them as background or mask images.

It generates code multiple icons from an icon set, splitting common code and icon-specific code. To generate code for one icon without splitting code, see [func]getIconCSS().

If instead of using icons as background or mask images, you want to use icons as content of pseudo-elements, see [func]getIconsContentCSS().

To use icons in HTML, all you need to do is create any element, such as [tag]span with class names for an icon set and icon.

Color

Monotone icons are rendered as mask image with background color set to [prop]currentColor. That means icon will use the same color as text.

To change icon color, simply change text color.

include: common/css-demo

Icons with palette are rendered as background image.

You can also use [prop]color option to convert monotone icon to icon with palette. See [str]Color option section below.

Usage

Function has the following parameters:

Function returns [type]string with stylesheet for icons.

Options

The [prop]options object has the following properties:

Result

Example of generated stylesheet:

/* Common code is combined in one class that should be added to each icon */
.icon--tabler {
	display: inline-block;
	width: 1em;
	height: 1em;
	background-color: currentColor;
	-webkit-mask: no-repeat center / 100%;
	mask: no-repeat center / 100%;
	-webkit-mask-image: var(--svg);
	mask-image: var(--svg);
}

/* SVG for each icon. Class name should be combined with common class name used above */
.icon--tabler--code {
	--svg: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cpath fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m7 8l-4 4l4 4m10-8l4 4l-4 4M14 4l-4 16'/%3E%3C/svg%3E");
}

.icon--tabler--crystal-ball {
	--svg: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cg fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='2'%3E%3Cpath d='M6.73 17.018a8 8 0 1 1 10.54 0'/%3E%3Cpath d='M5 19a2 2 0 0 0 2 2h10a2 2 0 1 0 0-4H7a2 2 0 0 0-2 2zm6-12a3 3 0 0 0-3 3'/%3E%3C/g%3E%3C/svg%3E");
}

.icon--tabler--view-360 {
	--svg: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cg fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='2'%3E%3Ccircle cx='12' cy='12' r='9'/%3E%3Cellipse cx='12' cy='12' rx='4' ry='9'/%3E%3Cpath d='M3 12c0 2.21 4.03 4 9 4s9-1.79 9-4s-4.03-4-9-4s-9 1.79-9 4z'/%3E%3C/g%3E%3C/svg%3E");
}

That code can be used in HTML with any element, such as [tag]span with class names for both common code and icon specific code:

<span class="icon--tabler icon--tabler--code"></span>

Color option

include: libraries/utils/css-color
<span
	class="icon--tabler icon--tabler--view-360"
	style="color: var(--icon-color)"
></span>

Selectors

Simple selector

If you want to change selectors to something simple, like [str].icon-home for [str]home icon, use the following options:

{
	"iconSelector": ".icon-{name}",
	"commonSelector": ""
}

It will result in stylesheet like this:

.icon-code,
.icon-crystal-ball,
.icon-view-360 {
	display: inline-block;
	width: 1em;
	height: 1em;
	background-color: currentColor;
	-webkit-mask: no-repeat center / 100%;
	mask: no-repeat center / 100%;
	-webkit-mask-image: var(--svg);
	mask-image: var(--svg);
}

.icon-code {
	--svg: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cpath fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m7 8l-4 4l4 4m10-8l4 4l-4 4M14 4l-4 16'/%3E%3C/svg%3E");
}

.icon-crystal-ball {
	--svg: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cg fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='2'%3E%3Cpath d='M6.73 17.018a8 8 0 1 1 10.54 0'/%3E%3Cpath d='M5 19a2 2 0 0 0 2 2h10a2 2 0 1 0 0-4H7a2 2 0 0 0-2 2zm6-12a3 3 0 0 0-3 3'/%3E%3C/g%3E%3C/svg%3E");
}

.icon-view-360 {
	--svg: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cg fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='2'%3E%3Ccircle cx='12' cy='12' r='9'/%3E%3Cellipse cx='12' cy='12' rx='4' ry='9'/%3E%3Cpath d='M3 12c0 2.21 4.03 4 9 4s9-1.79 9-4s-4.03-4-9-4s-9 1.79-9 4z'/%3E%3C/g%3E%3C/svg%3E");
}

Old browsers

If you need to support ancient browsers that do not support variables, set [prop]varName to null:

{
	"varName": null
}

It will result in CSS like this:

.icon--tabler {
	display: inline-block;
	width: 1em;
	height: 1em;
	background-color: currentColor;
	-webkit-mask: no-repeat center / 100%;
	mask: no-repeat center / 100%;
}

.icon--tabler--code {
	-webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cpath fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m7 8l-4 4l4 4m10-8l4 4l-4 4M14 4l-4 16'/%3E%3C/svg%3E");
	mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cpath fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m7 8l-4 4l4 4m10-8l4 4l-4 4M14 4l-4 16'/%3E%3C/svg%3E");
}

.icon--tabler--crystal-ball {
	-webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cg fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='2'%3E%3Cpath d='M6.73 17.018a8 8 0 1 1 10.54 0'/%3E%3Cpath d='M5 19a2 2 0 0 0 2 2h10a2 2 0 1 0 0-4H7a2 2 0 0 0-2 2zm6-12a3 3 0 0 0-3 3'/%3E%3C/g%3E%3C/svg%3E");
	mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cg fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='2'%3E%3Cpath d='M6.73 17.018a8 8 0 1 1 10.54 0'/%3E%3Cpath d='M5 19a2 2 0 0 0 2 2h10a2 2 0 1 0 0-4H7a2 2 0 0 0-2 2zm6-12a3 3 0 0 0-3 3'/%3E%3C/g%3E%3C/svg%3E");
}

With monotone icons it will cause duplication because some browsers still require prefix for masks.

Not needed for icons for palette because default value for icons with palette is null (see example below that uses icons with palette).

Wide and thin icons

Not all icons are square. Some icon sets use variable width for icons, this mostly applies to icon sets that were designed to be used as fonts.

By default, common code will have [prop]width set to [num]1em and it will be overridden by using selectors with higher specificity for each icon:

.icon--fa6-solid {
	display: inline-block;
	width: 1em;
	height: 1em;
	background-color: currentColor;
	-webkit-mask: no-repeat center / 100%;
	mask: no-repeat center / 100%;
	-webkit-mask-image: var(--svg);
	mask-image: var(--svg);
}

.icon--fa6-solid.icon--fa6-solid--angle-left {
	width: 0.63em;
	--svg: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 320 512' width='320' height='512'%3E%3Cpath fill='black' d='M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256l137.3-137.4c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z'/%3E%3C/svg%3E");
}

.icon--fa6-solid.icon--fa6-solid--arrow-left {
	width: 0.88em;
	--svg: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 448 512' width='448' height='512'%3E%3Cpath fill='black' d='M9.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.2 288H416c17.7 0 32-14.3 32-32s-14.3-32-32-32H109.3l105.3-105.4c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z'/%3E%3C/svg%3E");
}

But what if you want icons to be square? Use [prop]forceSquare option:

{
	"forceSquare": true
}
.icon--fa6-solid {
	display: inline-block;
	width: 1em;
	height: 1em;
	background-color: currentColor;
	-webkit-mask: no-repeat center / 100%;
	mask: no-repeat center / 100%;
	-webkit-mask-image: var(--svg);
	mask-image: var(--svg);
}

.icon--fa6-solid--angle-left {
	--svg: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 320 512' width='320' height='512'%3E%3Cpath fill='black' d='M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256l137.3-137.4c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z'/%3E%3C/svg%3E");
}

.icon--fa6-solid--arrow-left {
	--svg: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 448 512' width='448' height='512'%3E%3Cpath fill='black' d='M9.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.2 288H416c17.7 0 32-14.3 32-32s-14.3-32-32-32H109.3l105.3-105.4c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z'/%3E%3C/svg%3E");
}

Custom selectors

If you want to use custom selectors, such as [str].iconify-{name} for icons, specify 3 options:

If you set only [prop]iconSelector, other 2 options will be ignored.

Examples:

Using only 1 option

{
	"iconSelector": ".iconify-{name}"
}

Results in:

.iconify-alien,
.iconify-balance-scale {
	display: inline-block;
	width: 1em;
	height: 1em;
	background: no-repeat center / 100%;
}

.iconify-alien {
	background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32' width='32' height='32'%3E%3Cg fill='none'%3E%3Cpath fill='%2386D72F' d='M29.84 15.92C29.84 23.61 18.92 30 15.92 30S2 23.61 2 15.92S8.23 2 15.92 2c7.69 0 13.92 6.23 13.92 13.92Z'/%3E%3Cpath fill='%23212121' d='M13.368 24.225a1 1 0 0 1 1.407.143c.376.461.825.645 1.225.645c.4 0 .85-.184 1.225-.645a1 1 0 1 1 1.55 1.264c-.724.889-1.726 1.38-2.775 1.38c-1.05 0-2.05-.491-2.775-1.38a1 1 0 0 1 .143-1.407Z'/%3E%3Cpath fill='%23533566' d='M6.474 19.527c2.254 2.253 4.6 3.549 6.845 1.306c2.253-2.242 2.233-5.905-.01-8.147c-2.244-2.243-5.898-2.253-8.142 0c-2.243 2.253-.946 4.588 1.307 6.84Zm19.051 0c-2.255 2.253-4.602 3.549-6.847 1.306c-2.244-2.242-2.234-5.905.01-8.147c2.245-2.243 5.9-2.253 8.144 0c2.245 2.253.947 4.588-1.307 6.84Z'/%3E%3Cpath fill='%23fff' d='M12.62 15.62c.61-.61.47-1.73-.31-2.51c-.78-.77-1.9-.92-2.51-.31c-.61.61-.47 1.73.31 2.51c.78.78 1.9.92 2.51.31Zm13.28 0c.61-.61.47-1.73-.31-2.51c-.77-.77-1.9-.92-2.51-.31c-.61.61-.47 1.73.31 2.51c.78.78 1.9.92 2.51.31Z'/%3E%3C/g%3E%3C/svg%3E");
}

.iconify-balance-scale {
	background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32' width='32' height='32'%3E%3Cg fill='none'%3E%3Cpath fill='%239B9B9B' d='M19.949 11.75h4.02a.749.749 0 1 0 0-1.5h-4.02c-.38 0-.73-.18-.95-.48l-2.37-3.25a.765.765 0 0 0-.705-.296a.747.747 0 0 0-.585.306l-2.37 3.24c-.22.3-.58.48-.95.48h-4.02c-.41 0-.75.34-.75.75s.34.75.75.75h4.02c.85 0 1.66-.41 2.16-1.09l1.809-2.473l1.801 2.463c.5.69 1.31 1.1 2.16 1.1Z'/%3E%3Cpath fill='%23D3D3D3' d='M15.249 4h1.5v24h-1.5V4Zm-2.21 16.73c.09.15.26.23.42.23c.09 0 .18-.02.24-.08a.5.5 0 0 0 .15-.69l-5.372-8.338A.494.494 0 0 0 8 11.5c-.16 0-.45.27-.45.27l-5.39 8.38c-.07.08-.11.19-.11.31c0 .28.22.5.5.5c.17 0 .33-.09.42-.23l4.53-7.034V20.8c0 .28.22.5.5.5s.5-.22.5-.5v-7.105l4.54 7.035Zm16 0c.09.15.26.23.42.23c.09 0 .18-.02.24-.08a.5.5 0 0 0 .15-.69l-5.372-8.338A.494.494 0 0 0 24 11.5c-.16 0-.359.155-.45.27l-5.39 8.38c-.07.08-.11.19-.11.31c0 .28.22.5.5.5c.17 0 .33-.09.42-.23l4.53-7.034V20.8c0 .28.22.5.5.5s.5-.22.5-.5v-7.105l4.54 7.035Z'/%3E%3Cpath fill='%23F9C23C' d='M17.59 3.59a1.59 1.59 0 1 1-3.18 0a1.59 1.59 0 0 1 3.18 0Zm-8 7.41a1.59 1.59 0 1 1-3.181 0a1.59 1.59 0 0 1 3.18 0Zm-7.571 9.64c-.09-.32.15-.64.49-.64h10.98c.34 0 .58.32.49.64c-.74 2.56-3.13 4.36-5.98 4.36c-2.85 0-5.24-1.8-5.98-4.36Zm16 0c-.09-.32.15-.64.49-.64h10.98c.34 0 .58.32.49.64c-.74 2.56-3.13 4.36-5.98 4.36c-2.85 0-5.24-1.8-5.98-4.36ZM23.4 30c.48 0 .71-.58.36-.91A11.216 11.216 0 0 0 16 26c-3.01 0-5.74 1.17-7.76 3.09c-.35.33-.12.91.36.91h14.8Zm.6-17.41a1.59 1.59 0 1 0-.001-3.18a1.59 1.59 0 0 0 0 3.18Z'/%3E%3C/g%3E%3C/svg%3E");
}

Pseudo-selector

This example shows why [prop]overrideSelector is an option and how to render icons with pseudo-selectors:

{
	"iconSelector": ".icon--{prefix}--{name}::after",
	"commonSelector": ".icon--{prefix}::after",
	"overrideSelector": ".icon--{prefix}.icon--{prefix}--{name}::after",
	"pseudoSelector": true
}
.icon--fa6-solid::after {
	display: inline-block;
	width: 1em;
	height: 1em;
	content: '';
	background-color: currentColor;
	-webkit-mask: no-repeat center / 100%;
	mask: no-repeat center / 100%;
	-webkit-mask-image: var(--svg);
	mask-image: var(--svg);
}

.icon--fa6-solid.icon--fa6-solid--angle-left::after {
	width: 0.63em;
	--svg: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 320 512' width='320' height='512'%3E%3Cpath fill='black' d='M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256l137.3-137.4c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z'/%3E%3C/svg%3E");
}

.icon--fa6-solid.icon--fa6-solid--arrow-left::after {
	width: 0.88em;
	--svg: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 448 512' width='448' height='512'%3E%3Cpath fill='black' d='M9.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.2 288H416c17.7 0 32-14.3 32-32s-14.3-32-32-32H109.3l105.3-105.4c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z'/%3E%3C/svg%3E");
}

Example

Above examples show various options. This example shows actual code with options:

src: libraries/utils/get-icons-css.ts
title: 'generate-css.ts'
extra:
  - src: libraries/utils/get-icons-css.css
    title: 'Result:'
  - src: libraries/utils/get-icons-css.html
    title: 'Usage in HTML:'
Libraries

get-icons

title: getIcons() in Iconify Utils
types:
  IconifyJSON: '/docs/types/iconify-json.md'

getIcons()

This function is part of Iconify Utils package.

Function [func]getIcons() retrieves few icons from icon set.

Usage

Function has the following parameters:

Example

src: libraries/utils/get-icons.ts
title: 'usage.ts'
extra:
  - src: libraries/utils/get-icons.json
    title: 'Result:'
Libraries

get-svg-viewbox

title: getSVGViewBox() and SVGViewBox in Iconify Utils

getSVGViewBox() and SVGViewBox type

This function is part of Iconify Utils package.

Function [func]getSVGViewBox() is a helper function that parses [prop]viewBox attribute value.

Result is represented by [type]SVGViewBox type, used in various functions in Iconify Utils.

Usage

The function has the following parameter:

Function returns [type]SVGViewBox with parsed viewBox value or [type]undefined on error.

Function validates numbers to make sure values are valid numbers and there are exactly 4 numbers. On failure, it will return [type]undefined.

SVGViewBox type

Type [type]SVGViewBox is an array of four numbers:

Example

src: libraries/utils/get-svg-viewbox.ts
title: 'usage.ts'
extra:
  - src: libraries/utils/get-svg-viewbox.json
    title: 'Result:'

Convert to string

To get [prop]viewBox attribute as a string from [type]SVGViewBox, use [func]join function:

const value = viewBox.join(' ');
Libraries

icon-customisations

title: IconifyIconCustomisations Type
types:
  IconifyIconSize: './icon-customisations.md#icon-size'
functions:
  defaultIconCustomisations: './default-icon-customisations.md'
  iconToSVG: './icon-to-svg.md'
  mergeCustomisations: './merge-customisations.md'

IconifyIconCustomisations type

[type]IconifyIconCustomisations type is used in Iconify Utils in functions for generating SVG.

You can find this type in [file]src/customisations/defaults.ts of Iconify Utils source code.

Type is an object, with the following properties, split into groups:

Dimensions {#icon-size}

Icon dimensions, which has type [type]IconifyIconSizeCustomisations, have 2 properties:

Type [type]IconifyIconSize is alias for [type]null | string | number. Possible values are:

There are several special keywords:

When calculating icon dimensions, setting one dimension (usually [attr]height) is enough. Another dimension will be automatically calculated using icon's proportions.

If both [prop]width and [prop]height are not set or null, by default [prop]height will be set to [str]1em.

Transformations

Icon can be transformed. Transformations are done by rotating or flipping content inside SVG, these are not CSS transformations. Properties for transforming icon:

If you want to pick only transformations from customisations, use type [type]IconifyTransformations.

FullIconifyIconCustomisations type

Type [type]FullIconifyIconCustomisations is the same as [type]IconifyIconCustomisations, but all properties are required.

Use [func]defaultIconCustomisations constant to get all default values and merged it with your values:

src: libraries/utils/icon-customisations.ts
title: 'example.ts'

Then result can be used with [func]mergeCustomisations() function.

Also see [func]defaultIconCustomisations constant.

Libraries

icon-name

title: IconifyIconName Type

IconifyIconName type

[type]IconifyIconName type is used in Iconify Utils to handle icon names.

You can find this type in [file]src/icon/name.ts of Iconify Utils source code.

include types/iconify-icon-name

Validation

All parts of icon name must match the following regular expression: [js]/^[a-z0-9]+(-[a-z0-9]+)*$/.

The only exception is [prop]provider, which can be empty.

Expression for validation can be imported from Iconify Utils:

src: libraries/utils/match-name.ts
title: 'example.ts'
Libraries

icon-to-html

title: iconToHTML() in Iconify Utils
types:
  IconifyIconBuildResult: './icon-to-svg.md#build-result'
functions:
  iconToSVG: './icon-to-svg.md'
  parseSVGContent: './parse-svg-content.md'
  buildParsedSVG: './build-parsed-svg.md'

iconToHTML()

This function is part of Iconify Utils package.

Function [func]iconToHTML() generates SVG from a list of attributes for [tag]svg element and icon content.

It can be used with results of [func]iconToSVG(), [func]parseSVGContent() or [func]buildParsedSVG().

Usage

Function has the following parameters:

Function returns [type]string.

Notes

Function adds the following attributes automatically, do not add them in [prop]attributes parameter:

Attribute values are not modified. Make sure they are escaped before calling function.

Example

src: libraries/utils/get-icon.ts
title: 'example.ts'
Libraries

icon-to-svg

title: iconToSVG() in Iconify Utils
types:
  IconifyIconCustomisations: './icon-customisations.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
  IconifyIconBuildResult: './icon-to-svg.md#build-result'
  SVGViewBox: './get-svg-viewbox.md'
functions:
  iconToHTML: './icon-to-html.md'
  parseSVGContent: './parse-svg-content.md'
  buildParsedSVG: './build-parsed-svg.md'

iconToSVG()

This function is part of Iconify Utils package.

Function [func]iconToSVG() generates data required to render SVG.

Usage

This function has the following parameters:

This function returns data with type [type]IconifyIconBuildResult. See below.

Parsing SVG

This function uses [type]IconifyIcon as a source. If you want to parse a string that contains SVG, use [func]parseSVGContent() and [func]buildParsedSVG() functions instead.

Result {#build-result}

The result is an object with the following properties:

List of attributes in the result does not include [prop]xmlns because it is identical in all SVG. It always includes [prop]viewBox, usually includes [prop]width and [prop]height.

You can use [func]iconToHTML() to convert the result to string.

Examples of result

{
	"attributes": {
		"width": "24",
		"height": "24",
		"viewBox": "0 0 24 24"
	},
    "viewBox": [0, 0, 24, 24],
	"body": "<path d=\"M7 6v12l10-6z\" fill=\"currentColor\"/>"
}

Example

src: libraries/utils/get-icon.ts
title: 'example.ts'

Icon dimensions

By default, resulting attributes include [prop]width and [prop]height, where [prop]height is set to [str]1em.

If you want to remove dimensions, set [prop]height to [str]unset or [str]none in [prop]customisations parameter:

const result = iconToSVG(data, {
	// Setting only height will also remove width
	height: 'unset',
});
Libraries

index

title: Iconify Utils
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'

Iconify Utils

Iconify Utils is a set of reusable functions that are used by various Iconify icon components and related packages:

Library is written in TypeScript, is available as ES modules for modern development and CommonJS for older scripts.

Installation

To install library run:

npm install @iconify/utils --save

Examples

Documentation for each function below includes code samples.

In addition to that, there are several bigger code samples for specific commonly used tasks to help you figure out what functions to use.

Functions

include libraries/utils/functions-list

Advanced usage {#advanced}

Iconify Utils can do only basic parsing of [type]IconifyJSON and [type]IconifyIcon data. It is not meant for more complex stuff.

For more complex stuff, such as importing icons, validating icon code, changing palette, cleaning up, exporting to various formats, see Iconify Tools package.

Libraries

match-name

title: matchIconName in Iconify Utils
types:
  IconifyIconName: './icon-name.md'
functions:
  validateIconName: './validate-icon.md'

matchIconName

This constant is part of Iconify Utils package.

Constant [func]matchIconName is used to validate all parts of icon name.

The only exception is provider. API provider can be empty, so additional check for empty provider is needed.

This constant is used by [func]validateIconName().

Usage

import { matchIconName } from '@iconify/utils';

function checkIcon(name: string): boolean {
	return !!name.match(matchIconName);
}

console.log(checkIcon('test-icon') ? 'passed' : 'failed');
Libraries

merge-customisations

title: mergeCustomisations() in Iconify Utils
types:
  FullIconCustomisations: './icon-customisations.md'
  IconifyIconCustomisations: './icon-customisations.md'
  IconifyIconName: './icon-name.md'
functions:
  validateIconName: './validate-icon.md'

mergeCustomisations()

This function is part of Iconify Utils package.

Function [func]mergeCustomisations() merges default customisations, presented as [type]FullIconCustomisations object and partial customisations. It also validates types, so it can be used to clean up user input.

Usage

Function has the following parameters:

Function returns merged customisations with same type as passed in first parameter (which makes it possible to use function with extended types).

Example

src: libraries/utils/merge-customisations2.ts
title: 'example.ts'

Merge

Why not just merge objects, like this?

src: libraries/utils/merge-customisations.ts
title: 'bad-example.ts'

That works only with default customisations, but not if both objects have transformations.

Function [func]mergeCustomisations() should be used when, for example, you are merging customisations from icon, which might include transformations and user's customisations. It can also be used to merge customisations when resolving icon alias.

Libraries

merge-defs-and-content

title: mergeDefsAndContent() in Iconify Utils
functions:
  splitSVGDefs: './split-svg-defs.md'
  wrapSVGContent: './wrap-svg-content.md'
  iconToSVG: './icon-to-svg.md'
  buildParsedSVG: './build-parsed-svg.md'
  convertParsedSVG: './convert-parsed-svg.md'

mergeDefsAndContent()

This function is part of Iconify Utils package.

Function [func]splitSVGDefs() merges definitions and other SVG content in a string.

This function is used by [func]wrapSVGContent() to wrap icon content, which is used by [func]iconToSVG() to apply flip and rotation to icon, by [func]buildParsedSVG() and [func]convertParsedSVG() to move presentational attributes from [tag]svg element to a group element.

Usage

This function has the following parameters:

This function returns merged icon as a string.

Example

src: libraries/utils/split-svg-defs.ts
title: 'example.ts'
Libraries

merge-icon-data

title: mergeIconData() in Iconify Utils
types:
  IconifyIcon: '/docs/types/iconify-icon.md'
  IconifyOptional: '/docs/types/iconify-icon.md#iconify-optional'

mergeIconData()

This function is part of Iconify Utils package.

Function [func]mergeIconData() merges data for icon and alias.

Merging logic

When combining icon and alias, properties cannot be simply merged. This is because transformations for alias are relative to parent icons' transformations.

For example, if icon has 90 degrees rotation and alias also has 90 degrees rotation, result is 180 degrees rotation. Same for horizontal and vertical flip.

Usage

Function has the following parameters:

Function returns merged icon data.

Example

src: libraries/utils/merge-icon-data.ts
title: 'usage.ts'
extra:
  - src: libraries/utils/merge-icon-data.json
    title: 'Result 1:'
  - src: libraries/utils/merge-icon-data2.json
    title: 'Result 2:'
Libraries

minify-icon-set

title: minifyIconSet() in Iconify Utils
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
  IconifyDimensions: '../../types/iconify-icon.md#iconify-optional'
  FullIconifyIcon: './full-iconify-icon.md'

minifyIconSet()

This function is part of Iconify Utils package.

Function [func]minifyIconSet() optimises icon set, reducing file size.

Usage

Function has only one parameter:

Function does not create a new object, it modifies object passed to function.

What exactly does it do? {#explanation}

Icons in icon set have common properties, such as [prop]width and [prop]height:

{
	"prefix": "foo",
	"icons": {
		"icon1": {
			"body": "<path d=\"M7 6v12l10-6z\" fill=\"currentColor\"/>",
			"width": 24,
			"height": 24
		},
		"icon2": {
			"body": "<path d=\"M5 13v-1h6V6h1v6h6v1h-6v6h-1v-6H5z\" fill=\"currentColor\"/>",
			"width": 24,
			"height": 24
		},
		"icon3": {
			"body": "<path d=\"M10 8a2 2 0 1 1-4 0a2 2 0 0 1 4 0z\" fill=\"currentColor\"/>",
			"width": 16,
			"height": 16
		}
	}
}

In example above, icons [str]icon1 and [str]icon2 have identical [prop]width and [prop]height. To avoid duplication, these values can be moved to root object:

{
	"prefix": "foo",
	"icons": {
		"icon1": {
			"body": "<path d=\"M7 6v12l10-6z\" fill=\"currentColor\"/>"
		},
		"icon2": {
			"body": "<path d=\"M5 13v-1h6V6h1v6h6v1h-6v6h-1v-6H5z\" fill=\"currentColor\"/>"
		},
		"icon3": {
			"body": "<path d=\"M10 8a2 2 0 1 1-4 0a2 2 0 0 1 4 0z\" fill=\"currentColor\"/>",
			"width": 16,
			"height": 16
		}
	},
	"width": 24,
	"height": 24
}

Function [func]minifyIconSet() finds common properties in icon set and moves them to root object.

What properties can be minified? Properties defined in [type]IconifyDimensions type: [prop]left, [prop]top, [prop]width and [prop]height.

See [type]IconifyJSON type for more information.

In this example difference between original and minified files isn't big, but for large icon sets with thousands of icons it does make a big difference in file size.

Example

src: libraries/utils/minify.ts
title: 'usage.ts'
extra:
  - src: libraries/utils/minify.json
    title: 'Result:'
Libraries

parse-icon-set

title: parseIconSet() in Iconify Utils
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyInfo: '/docs/types/iconify-info.md'
  IconifyIcon: '/docs/types/iconify-icon.md'
functions:
  validateIconSet: './validate-icon-set.md'
  quicklyValidateIconSet: './quickly-validate-icon-set.md'

parseIconSet()

This function is part of Iconify Utils package.

Functions [func]parseIconSet() and [func]parseIconSetAsync() parse icon set, calling custom function for every icon.

Usage

Function has the following parameters:

Function returns names of parsed icons as [type]string[].

Callback

Callback function has 2 parameters:

Callback is called for each entry in icon set: all icons, aliases and all entries in [prop]not_found property.

If [prop]data parameter in callback is null, icon is invalid or missing.

parseIconSetAsync

Function [func]parseIconSetAsync() is identical to [func]parseIconSet(), except that it is asynchronous and callback is also an asynchronous function:

await parseIconSetAsync(iconSet, async (name, data) => {
	// do async stuff
});

Example

Exporting all icons from icon set:

src: libraries/utils/parse.ts
title: 'usage.ts'

Counting icons in icon set:

src: libraries/utils/count.ts
title: 'count.ts'

Code used in example above should be used to count icons in icon set when calculating number of icons for [type]IconifyInfo data. It counts all icons, excluding hidden icons and basic aliases.

Validation

Function does not check icon set for errors. Before using it, validate icon set using [func]validateIconSet() or [func]quicklyValidateIconSet().

JSON Modules

When using ES modules, examples above might require running node with [str]--experimental-json-modules flag.

Until JSON modules support in Node.js becomes stable, you can avoid using flag by replacing [func]import with [func]require() because [func]require() supports JSON files:

const { icons } = require('@iconify-json/codicon');
Libraries

parse-svg-content

title: parseSVGContent() in Iconify Utils
types:
  IconifyIcon: '/docs/types/iconify-icon.md'
  SVGViewBox: './get-svg-viewbox.md'
functions:
  buildParsedSVG: './build-parsed-svg.md'
  convertParsedSVG: './convert-parsed-svg.md'
  iconToHTML: './icon-to-html.md'

parseSVGContent()

This function is part of Iconify Utils package.

Function [func]parseSVGContent() parses string that contains SVG, extracts attributes for [tag]svg element and icon content.

Usage

This function has the following parameter:

This function returns data with type [type]ParsedSVGContent, [type]undefined on error. See below.

Result {#result}

The result is an object with the following properties:

Attributes are not checked.

The result should be passed to either [func]buildParsedSVG() or [func]convertParsedSVG(). Both functions do simple validation of attributes in [tag]svg element and convert it to usable data.

Iconify Tools

This function is very basic. For advanced parsing and clean up, use Iconify Tools.

Examples

Example using [func]parseSVGContent() with [func]buildParsedSVG() and [func]iconToHTML() to clean up icon:

src: libraries/utils/build-parsed-svg.ts
title: 'cleanup.ts'

Example using [func]parseSVGContent() with [func]convertParsedSVG() to get icon data in [type]IconifyIcon format, which can be used by various icon components:

src: libraries/utils/convert-parsed-svg.ts
title: 'convert.ts'
Libraries

quickly-validate-icon-set

title: quicklyValidateIconSet() in Iconify Utils
types:
  IconifyJSON: '/docs/types/iconify-json.md'
functions:
  validateIconSet: './validate-icon-set.md'

quicklyValidateIconSet()

This function is part of Iconify Utils package.

Function [func]quicklyValidateIconSet() validates icon set, returning cleaned up [type]IconifyJSON object.

If there are errors in provided data, it will return null.

This function does not check metadata.

Usage

Function has the following parameter:

Function returns:

Example

src: libraries/utils/quickly-validate.ts
title: 'usage.ts'

Advanced validation

This function is optimised for bundle size and performance, therefore it does only basic validation.

If you want to fully validate icon set, use [func]validateIconSet() instead.

Libraries

replace-ids

title: replaceIDs() in Iconify Utils
functions:
  iconToSVG: './icon-to-svg.md'

replaceIDs()

This function is part of Iconify Utils package.

Function [func]replaceIDs() is used for replacing IDs for icon content to avoid conflicts.

All icon components use this function for each rendered icon.

Why is it needed? {#explanation}

IDs are used in icon elements, such as reusable paths, masks, animations. They are supposed to be unique.

When icons are linked as external resources, this is not an issue. However, when icons are embedded in document, having multiple elements with the same ID from different icons can and will cause chaos. Even using the same icon in multiple places in document without changing IDs can cause errors.

This is why when embedding icons, it is important to never repeat the same IDs.

Usage

Function has the following parameter:

Function returns content with replaced IDs.

In first parameter you can pass [prop]body property of data generated by [func]iconToSVG() or you can pass an entire [tag]svg.

Example

src: libraries/utils/replace-ids.ts
title: 'example.ts'
extra:
  - src: libraries/utils/replace-ids.svg
    title: 'Result (first console.log):'
  - src: libraries/utils/replace-ids2.svg
    title: 'Result (second console.log):'

Conflicts

Replacement function will use original IDs to generate new IDs by adding numbers after original ID.

That means if icon has IDs [str]a, [str]b (for example, for clip paths) and so on, first icon will have IDs unchanged [str]a, [str]b, second icon will have IDs [str]a1, [str]b1 and so on.

In Iconify icon sets, all icons use unique IDs based on hash of their name and prefix, for example, [str]SVGqdEcMdXs. This ID is used only in one icon.

Because original ID is used to generate new ID, the first time icon is rendered, it will have ID [str]SVGqdEcMdXs (no changes), second time [str]SVGqdEcMdXs1 ([str]1 appended), third time [str]SVGqdEcMdXs2 ([str]2 appended) and so on.

This results in unique, but predictable IDs for each rendered icon.

Libraries

rotate-from-string

title: rotateFromString() in Iconify Utils
types:
  IconCustomisations: './icon-customisations.md'

rotateFromString()

This function is part of Iconify Utils package.

Function [func]rotateFromString() cleans up various possible values for ration passed by user to valid [prop]rotate property of [type]IconCustomisations type.

Usage

Function has the following parameter:

Function returns [type]number value in [num]0 to [num]3 range.

Example

src: libraries/utils/rotate-from-string.ts
title: 'demo.ts'
extra:
  - src: libraries/utils/rotate-from-string.txt
    title: 'Result:'
Libraries

split-svg-defs

title: splitSVGDefs() in Iconify Utils
functions:
  mergeDefsAndContent: './merge-defs-and-content.md'
  wrapSVGContent: './wrap-svg-content.md'
  iconToSVG: './icon-to-svg.md'
  buildParsedSVG: './build-parsed-svg.md'
  convertParsedSVG: './convert-parsed-svg.md'

splitSVGDefs()

This function is part of Iconify Utils package.

Function [func]splitSVGDefs() splits SVG body in contents of [tag]defs and other content.

This function is used by [func]wrapSVGContent() to wrap icon content, which is used by [func]iconToSVG() to apply flip and rotation to icon, by [func]buildParsedSVG() and [func]convertParsedSVG() to move presentational attributes from [tag]svg element to a group element.

Usage

This function has the following parameter:

This function returns an object with 2 properties:

To merge back definitions and content, use [func]mergeDefsAndContent().

Example

src: libraries/utils/split-svg-defs.ts
title: 'example.ts'
Libraries

string-to-color

title: stringToColor() in Iconify Utils
types:
  Color: './color.md'

stringToColor()

This function is part of Iconify Utils package.

Function [func]stringToColor() converts string to [type]Color object, returns null on error.

This function can be used to validate user input. It supports color keywords, hexadecimal colors, RGB, HSL, LAB and LCH colors. Variables are not supported because this is meant for parsing SVGs, which should not reference any external variables.

Usage

Function has one parameter:

Function returns [type]Color object on success, null on error.

Possible values

Colors that function can convert:

See [type]Color type description for details.

Examples

src: libraries/utils/string-to-color.ts
title: 'demo.ts'
Libraries

string-to-icon

title: stringToIcon() in Iconify Utils
types:
  IconifyIconName: './icon-name.md'
functions:
  validateIconName: './validate-icon.md'

stringToIcon()

This function is part of Iconify Utils package.

Function [func]stringToIcon() converts icon name string to [type]IconifyIconName object.

Usage

Function has the following parameters:

Function returns icon name with type [type]IconifyIconName on success, [type]null on failure.

Example

src: libraries/utils/string-to-icon.ts
title: 'examples.ts'
Libraries

to-boolean

title: toBoolean() in Iconify Utils
types:
  IconCustomisations: './icon-customisations.md'

toBoolean()

This function is part of Iconify Utils package.

Function [func]toBoolean() converts strings to boolean. It is used to parse various possible component property values to use them in [type]IconCustomisations properties.

Usage

Function has the following parameters:

Function returns [type]boolean value.

Example

src: libraries/utils/to-boolean.ts
title: 'demo.ts'
extra:
  - src: libraries/utils/to-boolean.txt
    title: 'Result:'
Libraries

validate-icon-set

title: validateIconSet() in Iconify Utils
types:
  IconifyJSON: '../../types/iconify-json.md'
functions:
  quicklyValidateIconSet: './quickly-validate-icon-set.md'

validateIconSet()

This function is part of Iconify Utils package.

Function [func]validateIconSet() validates icon set, returning cleaned up [type]IconifyJSON object.

If there are errors in provided data:

This function checks everything, including metadata.

Usage

Function has the following parameters:

Function returns:

If function encounters an error that cannot be fixed, function will throw an exception.

Options {#options}

Options object has the following properties:

Example

src: libraries/utils/validate.ts
title: 'usage.ts'

Quick validation

This function is quite big, so it is not recommended to bundle it for browser usage.

If you want to validate icon set in browser, such as when loading data from API in an icon component, use [func]quicklyValidateIconSet() instead. It is smaller and faster because it does not check metadata, does not attempt to fix errors.

Libraries

validate-icon

title: validateIconName() in Iconify Utils
types:
  IconifyIconName: './icon-name.md'

validateIconName()

This function is part of Iconify Utils package.

Function [func]validateIconName() validates icon name.

Usage

Function has the following parameters:

Function returns [type]boolean value.

Example

src: libraries/utils/validate-icon.ts
title: 'examples.ts'
Libraries

wrap-svg-content

title: wrapSVGContent() in Iconify Utils
functions:
  mergeDefsAndContent: './merge-defs-and-content.md'
  splitSVGDefs: './split-svg-defs.md'
  iconToSVG: './icon-to-svg.md'
  buildParsedSVG: './build-parsed-svg.md'
  convertParsedSVG: './convert-parsed-svg.md'

wrapSVGContent()

This function is part of Iconify Utils package.

Function [func]wrapSVGContent() wraps icon body in custom code.

It is used by [func]iconToSVG() to apply flip and rotation to icon, by [func]buildParsedSVG() and [func]convertParsedSVG() to move presentational attributes from [tag]svg element to a group element.

Usage

This function has the following parameters:

This function extracts definitions from icon content, merges the rest of icon as [str]start + content + end, merges it with previously extracted definitions.

Example

src: libraries/utils/split-svg-defs.ts
title: 'example.ts'
Libraries

export-svg-from-data

title: 'Iconify Utils Code Examples: Export SVG'
functions:
  getIconData: '../get-icon-data.md'
  iconToSVG: '../icon-to-svg.md'
  replaceIDs: '../replace-ids.md'
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'

Export SVG using Iconify Utils

This tutorial is part of code examples for Iconify Utils.

Export SVG

This is an example of using Iconify Utils to generate SVG from icon data:

src: libraries/utils/svg-from-icon.ts
title: 'demo.ts'

Functions

Functions used in this code sample:

Source

For icon data source, this example uses hardcoded [type]IconifyIcon data.

You can import individual icon from split icon set package.

Output

This example outputs SVG to console.

If you need to write it to a file, use file system function, such as [func]writeFileSync() or one of its asynchronous counterparts.

Libraries

export-svg-from-icon-set

title: 'Iconify Utils Code Examples: Export SVG'
functions:
  getIconData: '../get-icon-data.md'
  iconToSVG: '../icon-to-svg.md'
  iconToHTML: '../icon-to-html.md'
  replaceIDs: '../replace-ids.md'
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'

Export SVG using Iconify Utils

This tutorial is part of code examples for Iconify Utils.

Export SVG

This is an example of using Iconify Utils to generate SVG from an icon set:

src: libraries/utils/svg-from-set.ts
title: 'demo.ts'

Async example

This is another example that:

src: usage/svg-utils.js
title: 'demo.js'

Functions

Functions used in this code sample:

Source

For icon set source, this example uses individual icon set package.

If you need to read from a different file, replace that code with something like this:

import { readFileSync } from 'fs';

const icons = JSON.parse(readFileSync('whatever.json', 'utf8'));

Typecast it to [type]IconifyJSON if you are using TypeScript:

import type { IconifyJSON } from '@iconify/types';
import { readFileSync } from 'fs';

const icons = JSON.parse(readFileSync('whatever.json', 'utf8')) as IconifyJSON;

Output

Example outputs SVG to console.

If you need to write it to a file, use file system function, such as [func]writeFileSync() or one of its asynchronous counterparts.

Icon size

In this example all generated icons have [prop]height="1em".

You can remove that by adding customisations as second parameter to [func]iconToSVG():

const renderData = iconToSVG(iconData, {
	// 'unset' removes dimensions from icon
	height: 'unset',
});
Libraries

export-svgs-from-icon-set

title: 'Iconify Utils Code Examples: Export SVG'
functions:
  parseIconSet: '../parse-icon-set.md'
  iconToSVG: '../icon-to-svg.md'
  replaceIDs: '../replace-ids.md'
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'

Export SVGs using Iconify Utils

This tutorial is part of code examples for Iconify Utils.

Export SVGs

This is an example of using Iconify Utils to generate SVGs from the icon set:

src: libraries/utils/svgs-from-set.ts
title: 'demo.ts'

Functions

Functions used in this code sample:

Source

For icon set source, this example uses [file].json file in [type]IconifyJSON format.

You can also use individual icon set package or full icon sets package. Point [var]source variable to [file].json file from one of those packages.

Output

This example writes all SVGs to the file system. Change [var]target variable to point to different directory.

Libraries

generate-css

title: 'Iconify Utils Code Examples: Generate CSS'
functions:
  getIconsCSS: '../get-icons-css.md'
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'

Generate CSS using Iconify Utils

This tutorial is part of code examples for Iconify Utils.

Generate CSS

This is an example of using Iconify Utils to generate CSS from icon data:

src: usage/css-utils.js
title: 'demo.js'

Functions

Functions used in this code sample:

Source

For icon data source, this example uses [npm]@iconify/json package.

Output

This example writes CSS to a file.

Libraries

index

title: Iconify Utils Code Examples
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyIcon: '/docs/types/iconify-icon.md'

Code examples for Iconify Utils

Documentation for each function in Iconify Utils includes code samples.

However, how to figure out which function to look at? Below are code samples for common use cases.

Export icon set

Examples to export an entire icon set:

Export single SVG

Examples of generating a single SVG file:

Export CSS

Examples to export icons as CSS:

Advanced import / export {#advanced}

Iconify Utils is a basic package that parses [type]IconifyJSON and [type]IconifyIcon data. It is not meant for more complex stuff.

For more complex stuff, such as importing icons, validating icon code, changing palette, cleaning up, exporting to various formats, see Iconify Tools package.

Types

Types

iconify-alias

title: Iconify Alias Type
types:
  IconifyIcon: './iconify-icon.md'
  IconifyJSON: './iconify-json.md'

IconifyAlias type

All Iconify libraries share common object structures. They are described as types in [npm]@iconify/types NPM package.

For description of types and short explanation of TypeScript see types documentation.

This article describes [type]IconifyAlias type.

IconifyAlias type {#iconify-alias}

Type [type]IconifyAlias represents an alias for icon. It is used in Iconify JSON files.

What is an alias? An alias is icon that reuses another icon's properties.

[icon]arrow-left could be an alias of [icon]arrow-right with horizontal flip enabled. No need to create new shape when existing shape can be reused with a simple transformation.

[icon]battery-empty could be an alias of [icon]battery-0 without any changes. This makes it possible to assign multiple names to the same icon.

Structure

Type [type]IconifyAlias is similar to [type]IconifyIcon.

Properties:

Other properties are from [type]IconifyOptional type, they are shared with [type]IconifyIcon type.

include types/iconify-optional

Parent icon

Parent icon name should not include icon set prefix, and parent icon must be present in the icon set.

If you use another alias as a parent, make sure there are no circular dependencies. For example, if [icon]arrow-left is an alias of [icon]arrow-right (with horizontal flip), which in turn is an alias of [icon]arrow-up (with 90 degrees rotation), which in turn is an alias of [icon]arrow-down (with vertical flip), [icon]arrow-down could not be an alias of [icon]arrow-left because that would create a loop.

To be safe, use only icons as parent, not other aliases.

Merging properties for icon and alias

If, when merging properties, an icon alias has a property that parent icon also has, the following rules apply:

For all other properties alias overrides parent icon's value.

Examples of merging icon and alias:

src: types/icon-merge1.json
title: 'Icon:'
extra:
  - src: types/icon-merge1-alias.json
    title: 'Alias:'
  - src: types/icon-merge1-result.json
    title: 'Merged:'

In the example above, [js]hFlip + hFlip = false, [js]!vFlip /* default value */ + vFlip = true, icon alias overwrote other properties.

Examples

src: types/alias-raw.json
title: 'IconifyAlias:'
extra:
  - src: types/alias-json.json
    title: 'IconifyJSON:'
  - src: types/alias-merged.json
    title: 'Merged "arrow-right" icon as IconifyIcon:'
src: types/alias2-raw.json
title: 'IconifyAlias:'
extra:
  - src: types/alias2-json.json
    title: 'IconifyJSON:'
  - src: types/alias2-merged.json
    title: 'Merged "home" icon as IconifyIcon:'
src: types/alias3-raw.json
title: 'IconifyAlias:'
extra:
  - src: types/alias3-json.json
    title: 'IconifyJSON:'
  - src: types/alias3-merged.json
    title: 'Merged "house-32" icon as IconifyIcon:'
Types

iconify-icon

title: Iconify Icon Type
types:
  IconifyAlias: './iconify-alias.md'
  IconifyJSON: './iconify-json.md'
functions:
  getIconData: '../libraries/utils/get-icon-data.md'
  defaultIconProps: '../libraries/utils/default-icon-props.md'
  getIcon: '../libraries/tools/svg/index.md'

IconifyIcon type

All Iconify libraries share common object structures. They are described as types in [npm]@iconify/types NPM package.

For description of types and short explanation of TypeScript see types documentation.

This article describes [type]IconifyIcon type that contains data for one icon.

Usage

Icon data in [type]IconifyIcon type is usually extracted from [type]IconifyJSON icon set.

To extract icon data in your code, use [func]getIconData() function from Iconify Utils. Iconify Utils can be used in any environment.

To convert SVG to [type]IconifyIcon, you can use [func]getIcon() function of [type]SVG instance from Iconify Tools. Iconify Tools is a Node.js package for importing and parsing icons. Make sure you clean up icon before exporting it.

Structure

Type [type]IconifyIcon is a simple object. It has two parts:

Example of a basic icon:

src: types/icon-basic.json
copy: false

Body

Body contains contents of [tag]svg, without [tag]svg tag.

It does not include [tag]svg tag because:

Optional properties {#iconify-optional}

There are several properties that are shared in multiple types. They are described in [type]IconifyOptional type.

include types/iconify-optional

Example of typical icon data:

src: types/icon-basic2.json
copy: false

In your code you can get default values from [var]defaultIconProps constant from Iconify Utils.

Types

iconify-info

title: Iconify Info Type

IconifyInfo type

All Iconify libraries share common object structures. They are described as types in [npm]@iconify/types NPM package.

For description of types and short explanation of TypeScript see types documentation.

This article describes [type]IconifyAlias type.

Structure

Type [type]IconifyInfo is used for information about icon set.

It has the following mandatory properties:

Then it has many optional properties, most of these properties are intended for displaying icon set data in list of icon sets:

Author

[prop]author property is an object with following properties:

License

[prop]license property is an object with following properties:

Examples

{
	"name": "Phosphor",
	"total": 5206,
	"version": "1.3.2",
	"author": {
		"name": "Phosphor Icons",
		"url": "https://github.com/phosphor-icons/phosphor-icons"
	},
	"license": {
		"title": "MIT",
		"spdx": "MIT"
	},
	"samples": [
		"folder-notch-open-duotone",
		"check-square-offset-thin",
		"pencil-line-fill"
	],
	"height": 24,
	"displayHeight": 24,
	"category": "General",
	"palette": false
}
{
	"name": "Emoji One (Colored)",
	"total": 1834,
	"version": "2.3.0",
	"author": {
		"name": "Emoji One",
		"url": "https://github.com/EmojiTwo/emojitwo"
	},
	"license": {
		"title": "CC BY 4.0",
		"spdx": "CC-BY-4.0",
		"url": "https://creativecommons.org/licenses/by/4.0/"
	},
	"samples": [
		"anxious-face-with-sweat",
		"cloud-with-snow",
		"studio-microphone"
	],
	"height": 32,
	"displayHeight": 16,
	"category": "Emoji",
	"palette": true
}
Types

iconify-json-metadata

title: Iconify JSON Metadata
types:
  IconifyIcon: './iconify-icon.md'
  IconifyAlias: './iconify-alias.md'
  IconifyJSON: './iconify-json.md'
  IconifyInfo: './iconify-info.md'

IconifyJSON metadata

[type]IconifyJSON can also contain additional data that is used for displaying a list of icons:

Last modification time {#last-modified}

Last modification time is used to check if an icon set was updated. Icon components use it to invalidate old cache.

Value is a number, which needs to be higher than in a previously released version of an icon set.

Information {#iconify-info}

Information is stored in [prop]info object.

See [type]IconifyInfo documentation.

Categories {#iconify-categories}

Categories are stored in [prop]categories object.

In TypeScript categories are represented by type [type]IconifyCategories that can be imported from [npm]@iconify/types.

This is a simple object, where key is category name, value is an array of icon names that belong to that category.

Example:

{
	"categories": {
		"Accessibility": ["accessible-icon"],
		"Audio & Video": ["youtube"],
		"Communication": ["bluetooth", "bluetooth-b"],
		"Currency": ["bitcoin", "btc", "ethereum", "gg", "gg-circle"],
		"Games": [
			"playstation",
			"steam",
			"steam-square",
			"steam-symbol",
			"twitch",
			"xbox"
		]
	}
}

Themes: prefixes and suffixes {#themes}

Themes are used to display variations of the same icon that have different prefix or suffix. It is similar to categories, but instead of listing every icon, data contains only prefixes or suffixes.

Themes are stored in [prop]prefixes and [prop]suffixes objects.

In TypeScript both [prop]prefixes and [prop]suffixes are simple [type]Record<string, string> objects, where:

Example of prefixes used in Google Material Icons:

{
    "prefixes": {
        "baseline": "Baseline",
        "outline": "Outline",
        "round": "Round",
        "sharp": "Sharp",
        "twotone": "Two-Tone"
    }
}

In an example above, all icons that start with [icon]baseline- belong to [str]Baseline theme and so on.

When checking if icon belongs to a prefix, add [str]- to prefix. For example, [str]baseline-home belongs to [str]Baseline theme in example above, [str]baselinehome does not, because [str]- should separate prefix and icon name.

Example of suffixes used in Ant Design Icons:

{
    "suffixes": {
        "filled": "Filled",
        "outlined": "Outlined",
        "twotone": "TwoTone"
    }
}

In an example above, all icons that end with [str]-filled belong to [str]Filled theme, all icons that end with [str]-outlined belong to [str]Outlined theme and all icons that end with [str]-twotone belong to [str]TwoTone theme.

Default theme

Both prefixes and suffixes can have default entry, where the key is an empty string. Icons that do not fit other themes should be put in that theme.

Example:

{
    "suffixes": {
        "": "Filled",
        "outline": "Outline",
        "negative": "Negative"
    }
}

Icons that end with [str]-outline belong to [str]Outline theme, icons that end with [str]-negative belong to [str]Negative theme, all other icons belong to [str]Filled theme.

Legacy themes

In older versions of metadata, themes were stored in [prop]themes property. This has been deprecated and should be ignored.

Characters map {#chars}

Map of characters is stored in [prop]chars object.

In TypeScript characters are represented by type [type]IconifyChars that can be imported from [npm]@iconify/types.

This is a simple object, where key is character code in hexadecimal form, value is name of icon.

Example:

{
	"chars": {
		"e007": "firefox-browser",
		"e013": "ideal",
		"e01a": "microblog",
		"e01e": "pied-piper-square",
		"e049": "unity",
		"e052": "dailymotion",
		"e055": "instagram-square",
		"e056": "mixer",
		"e057": "shopify"
	}
}
Types

iconify-json

title: Iconify JSON Type
types:
  IconifyIcon: './iconify-icon.md'
  IconifyAlias: './iconify-alias.md'
functions:
  getIconData: '/docs/libraries/utils/get-icon-data.md'
  parseIconSet: '/docs/libraries/utils/parse-icon-set.md'
  defaultIconProps: '/docs/libraries/utils/default-icon-props.md'

IconifyJSON type

All Iconify libraries share common object structures. They are described as types in [npm]@iconify/types NPM package.

For description of types and short explanation of TypeScript see types documentation.

This article describes [type]IconifyJSON type.

Usage

Icon set in [type]IconifyJSON is created by Iconify Tools or loaded from pre-parsed JSON file.

See Iconify Utils documentation for parsing icon sets and icon sets package documentation.

See Iconify Tools documentation for creating custom icon sets.

Structure

Type [type]IconifyJSON is an object that has the following required properties.

Required properties

Example:

{
	"prefix": "mdi",
	"icons": {
		"home": {
			"body": "<path d=\"M10 20v-6h4v6h5v-8h3L12 3L2 12h3v8h5z\" fill=\"currentColor\"/>",
			"width": 24,
			"height": 24
		}
	}
}

Other properties are optional: aliases, default values for all icons, metadata.

Icon

Object [prop]icons contains data for icons.

Key is icon name. Value is icon data, where [prop]body is required and other properties are optional:

include types/iconify-optional

In your code you can get default values from [var]defaultIconProps constant from Iconify Utils.

Alias

One optional property of [type]IconifyJSON type is [prop]alias, which has type [type]Record<string, IconifyAlias>. Key is alias name, value is [type]IconifyAlias alias data. It represents a list of icon aliases.

What are aliases? They are variations of other icons. Aliases are used to reduce duplications.

For example, if icons [icon]home and [icon]house are identical, only one of those icons can be present in [prop]icons property, another icon can be listed in [prop]aliases, pointing to original icon:

{
	"prefix": "mdi",
	"icons": {
		"house": {
			"body": "<path d=\"M10 20v-6h4v6h5v-8h3L12 3L2 12h3v8h5z\" fill=\"currentColor\"/>",
			"width": 24,
			"height": 24
		}
	},
	"aliases": {
		"home": {
			"parent": "house"
		}
	}
}

Aliases can also include transformations: horizontal and/or vertical flip, 90/180/270 degrees rotation. This allows icon variations by reusing another icon, such as creating a right arrow by using left arrow with horizontal flip:

{
	"prefix": "bi",
	"icons": {
		"arrow-left": {
			"body": "<g fill=\"currentColor\"><path fill-rule=\"evenodd\" d=\"M5.854 4.646a.5.5 0 0 1 0 .708L3.207 8l2.647 2.646a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 0 1 .708 0z\"/><path fill-rule=\"evenodd\" d=\"M2.5 8a.5.5 0 0 1 .5-.5h10.5a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5z\"/></g>",
			"width": 16,
			"height": 16
		}
	},
	"aliases": {
		"arrow-right": {
			"parent": "arrow-left",
			"hFlip": true
		}
	}
}

Alias has the same properties as icons, except for [prop]body. It also has additional required property [prop]parent that points to parent icon.

Logic for resolving properties of alias:

src: types/alias-json.json
title: 'Source icon set:'
hint: 'Icon set as IconifyJSON'
extra:
  - src: types/alias-merged.json
    title: 'Extracted alias:'
    hint: 'Merged "arrow-right" icon as IconifyIcon'

Another example:

src: types/alias3-json.json
title: 'Source icon set:'
hint: 'Icon set as IconifyJSON'
extra:
  - src: types/alias3-merged.json
    title: 'Extracted alias:'
    hint: 'Merged "house-32" icon as IconifyIcon'

Default dimensions

If most icons in an icon set have the same dimensions, it does not make sense to list them all for each icon:

{
	"prefix": "mdi",
	"icons": {
		"home": {
			"body": "<path fill=\"currentColor\" d=\"M10 20v-6h4v6h5v-8h3L12 3L2 12h3v8h5Z\"/>",
			"width": 24,
			"height": 24
		},
		"account": {
			"body": "<path fill=\"currentColor\" d=\"M12 4a4 4 0 0 1 4 4a4 4 0 0 1-4 4a4 4 0 0 1-4-4a4 4 0 0 1 4-4m0 10c4.42 0 8 1.79 8 4v2H4v-2c0-2.21 3.58-4 8-4Z\"/>",
			"width": 24,
			"height": 24
		},
		"arrow-left": {
			"body": "<path fill=\"currentColor\" d=\"M20 11v2H8l5.5 5.5l-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5L8 11h12Z\"/>",
			"width": 24,
			"height": 24
		}
	}
}

To reduce that duplication, root of [type]IconifyJSON object might include default values for icon dimensions:

{
	"prefix": "mdi",
	"icons": {
		"home": {
			"body": "<path fill=\"currentColor\" d=\"M10 20v-6h4v6h5v-8h3L12 3L2 12h3v8h5Z\"/>"
		},
		"account": {
			"body": "<path fill=\"currentColor\" d=\"M12 4a4 4 0 0 1 4 4a4 4 0 0 1-4 4a4 4 0 0 1-4-4a4 4 0 0 1 4-4m0 10c4.42 0 8 1.79 8 4v2H4v-2c0-2.21 3.58-4 8-4Z\"/>"
		},
		"arrow-left": {
			"body": "<path fill=\"currentColor\" d=\"M20 11v2H8l5.5 5.5l-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5L8 11h12Z\"/>"
		}
	},
	"width": 24,
	"height": 24
}

These default values are used only for icons that do not have dimensions:

src: types/json-defaults-source.json
title: 'With default values:'
extra:
  - src: types/json-defaults-merged.json
    title: 'Without default values:'
    hint: 'Both examples are identical, first example has default values, second example does not.'

If dimensions in an icon are missing, and default values in the root object are missing, default value for property (see the list of properties above) is used:

src: types/json-defaults2-source.json
title: 'Icon without dimensions, which default to 16:'
extra:
  - src: types/json-defaults2-merged.json
    title: 'Icon with dimensions:'
    hint: 'Both examples are identical, first example has default property values, second example has explicit dimensions.'

In all examples above, [prop]width and [prop]height are used to demonstrate dimensions. But there are also [prop]left and [prop]top properties and transformations, which are missing in all examples. This is example above with all properties resolved:

{
	"prefix": "bi",
	"icons": {
		"arrow-left": {
			"body": "<g fill=\"currentColor\"><path fill-rule=\"evenodd\" d=\"M5.854 4.646a.5.5 0 0 1 0 .708L3.207 8l2.647 2.646a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 0 1 .708 0z\"/><path fill-rule=\"evenodd\" d=\"M2.5 8a.5.5 0 0 1 .5-.5h10.5a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5z\"/></g>",
			"width": 16,
			"height": 16,
			"left": 0,
			"top": 0,
			"hFlip": false,
			"vFlip": false,
			"rotate": false
		}
	}
}

Metadata

[type]IconifyJSON can also contain additional data that is used for displaying list of icons.

This is optional data that has no effect on rendering icons, so it was moved to a separate document.

See IconifyJSON metadata for details.

Functions

To parse icon sets, Iconify Utils offers the following functions:

To create convert icons to icon sets, use Iconify Tools.

Types

index

title: Iconify Types
types:
  IconifyIcon: './iconify-icon.md'
  IconifyAlias: './iconify-alias.md'
  IconifyJSON: './iconify-json.md'
  IconifyInfo: './iconify-info.md'

Iconify types

All Iconify libraries share common object structures. They are described as types in [npm]@iconify/types NPM package.

TypeScript

All types are described with TypeScript.

If you are not familiar with TypeScript, but are familiar with JavaScript, it should not be hard to understand this documentation because it is mostly just basic types.

Few basic TypeScript concepts you need to know to understand documentation:

Record

Type [type]Record<string, number> is an object, where key is [type]string, value is [type]number.

For PHP developers it is the same as associative array.

unknown

Type [type]unknown means value can be any type.

extends

src: types/interface.ts
copy: false

This means one type extends another type. In the example above, type [type]Foo has all properties of types [type]Bar and [type]Baz.

Main types

There are two main types that are used in Iconify ecosystem:

Additional types

These types are used in [type]IconifyJSON type:

Usage

Usage

index

title: How to use icons
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "60k"
    value: "${counters.icons-short}"

How to use icons

How to use icons in your projects?

Iconify ecosystem offers many ways to use icons, for both coders and designers.

HTML {#html}

For using icons in HTML, there are several viable options:

include usage/options/html

SVG + CSS {#svg-css}

SVG + CSS is the preferred solution because it:

However, due to complexity and poor browser support, implementation is available only for limited number of frameworks.

See how to use icons as SVG + CSS.

SVG in CSS {#css}

How to use icons in CSS:

Using icons as background images works great for icons with hardcoded palette, such as emojis.

Using icons as mask images, in combination with setting background color to [prop]currentColor, allows using monotone icons in CSS. To change icon color, simply change text color.

Example showing icons used as background and mask images (hover to see color change):

include: usage/css-demo

See how to use icons in CSS for various tools and plug-ins that make it easy to add icons to CSS.

SVG in HTML {#svg}

Icons can be embedded in HTML as [tag]svg elements:

src: usage/sample.svg
copy: false

See how to add SVG to HTML for various tools and components that make it easy to add icons to HTML.

Icons on demand

Iconify ecosystem has a unique feature: Iconify API.

It is used by various icon components to load icon data on demand. Iconify icon components only load icon data for icons used on the page visitor is viewing, at run time, instead of bundling icons.

Iconify icon components are perfect for complex projects like theme or website customisers, customisable admin panels or any similar projects, where icons can be customised by user.

Iconify icon components are very easy to use. All a developer has to specify is an icon name:

src: icon-components/icon/usage.html
copy: false

See how to use Iconify icon components.

Design

For designers, Iconify ecosystem offers several ways to easily import icons in various design tools.

include usage/options/design

Browse icons

You can browse and search more than 60k open source icons at one of the following websites:

include usage/options/websites

Find icon you want to use, select it, copy SVG to clipboard, paste it to your favorite design tool.

Possible issues:

Usage

index

title: How to use icons in CSS
functions:
  getIconsCSS: "/docs/libraries/utils/get-icons-css.md"
  getIconCSS: "/docs/libraries/utils/get-icon-css.md"

How to use icons in CSS

Using icons in CSS is easy: set icon as background or mask image, use simple [tag]span element in HTML to render icon.

Skip to list of available tools if you want to skip long explanation of how it all works.

Advantages

There are advantages and disadvantages of using SVG in CSS over using SVG in HTML.

Advantages:

However, it also has disadvantages:

How icons are rendered

There are two types of icons:

You can use both types in CSS.

Icons with palette

Icons with hardcoded palette can be rendered as background images:

src: usage/css-demo-bg.html
css: usage/css-demo-bg.scss
demo: true
demoFirst: true
class: usage-css-demo

Rendering as content {#content}

Icons with hardcoded palette can also be rendered as content of pseudo-elements.

It is similar to using icons as background images, but with a difference: icon's size cannot be controlled with CSS. You need to set width and height in SVG in pixels.

src: usage/css-demo-content.html
css: usage/css-demo-content.scss
demo: true
demoFirst: true
class: usage-css-demo

There are no clear advantages of rendering icons as content of pseudo-elements instead of background images.

Monotone icons {#monotone}

Monotone icons can be rendered as mask images with background color set to [prop]currentColor:

src: usage/css-demo-mask.html
css: usage/css-demo-mask.scss
demo: true
demoFirst: true
class: usage-css-demo

Using [prop]currentColor as background color makes it easy to change icon color by changing text color.

Tools

How to generate CSS for icons in the Iconify ecosystem?

There are several ways to do it:

Custom plugin

Want to build a custom plugin that generates CSS?

Iconify Utils package includes all functions you need. Process of generating CSS is simple:

Code samples that should help you:

Animated icons

Animated icons should not be used in CSS.

Issue is animation timers.

It would be reasonable to expect animation to start when icon is rendered, but that is not the case in CSS.

In CSS for background and mask images, animation timer starts the first time icon is rendered, then the same timer is used for all instances of icon. Animation timer cannot be reset.

Usage

index

title: CSS for icons without coding
replacements:
  - code: '60,000'
    value: '${counters.icons}'
  - code: '60k'
    value: '${counters.icons-short}'
  - code: '70 icon sets'
    value: '${counters.sets} icon sets'
  - code: '70 open source'
    value: '${counters.sets} open source'
functions:
  getIconsCSS: '/docs/libraries/utils/get-icons-css.md'

CSS for icons without coding

You can generate CSS for icons without writing any code, using Iconify API.

If you would rather generate CSS programmatically, consider using Iconify Utils.

API

Iconify API is an open source hosted (or self-hosted) service for developers. Public Iconify API servers host over 60,000 icons from more than 70 open source icon sets.

Public API is available at [url]https://api.iconify.design.

Among other features, it can generate CSS for icons. Query for CSS is [url]/{prefix}.css?icons={icons}, where:

Usage

Getting CSS is easy:

To use those icons in HTML, use [tag]span elements with 2 class names: class name for the icon set, class name for the icon.

<span class="icon--mdi-light icon--mdi-light--alert-circle"></span>

There is a bit of duplication in class names, as both the icon set and the icon contain the same first part. You can change it with options. See below.

Examples

/mdi-light.css?icons=alert-circle,circle,help-circle:

hint: /mdi-light.css?icons=alert-circle,circle,help-circle
src: api/mdi-light.css

/openmoji.css?icons=axe,balance-scale:

hint: /openmoji.css?icons=axe,balance-scale
src: api/openmoji.css

/mdi.css?icons=account-box,account-cash,account,home:

hint: /mdi.css?icons=account-box,account-cash,account,home
src: api/mdi.css

Options

API query has optional params that you can use to get different results.

See API query documentation for more details.

Usage

clean

title: Clean Class Names in Iconify for Tailwind CSS
types:
  IconifyJSON: '/docs/types/iconify-json.md'
functions:
  addDynamicIconSelectors: './index.md'
  getIconsCSS: '/docs/libraries/utils/get-icons-css.md'

Clean class names for Tailwind CSS

Iconify plugin for Tailwind CSS package has several plugins. This documentation covers [func]addCleanIconSelectors plugin.

Function [func]addCleanIconSelectors() creates icons with clean class names.

Deprecation notice

This plugin is deprecated!

It has been replaced with addIconSelectors plugin.

Usage

Open [file]tailwind.config.js, import [func]addCleanIconSelectors from [npm]@iconify/tailwind and add it to the list of plugins.

Example [file]tailwind.config.js:

const { addCleanIconSelectors } = require('@iconify/tailwind');

/** @type {import('tailwindcss').Config} */
module.exports = {
	content: ['./src/*.html'],
	plugins: [
		// Iconify plugin: clean version
		addCleanIconSelectors(['mdi-light:home']),
	],
};

Example icon with clean class names:

<span class="icon--mdi-light icon--mdi-light--home"></span>

Note that element has two class names:

By putting common rules in [str]icon--mdi-light, there is less duplicate code in generated CSS, which is much cleaner.

Parameters

There are 2 parameters for [func]addCleanIconSelectors():

Icon names

Unlike [func]addDynamicIconSelectors(), this plugin requires list of used icons.

This is needed because of Tailwind CSS limitations. For classes like [str]icon--mdi-light--home it is not possible to create Tailwind CSS plugin that matches partial class, like all classes that start with [str]icon--. Such functionality is possible only for classes that include [str]-[something], like [str]icon-[mdi-light--home].

The value of the first parameter is an array of strings or comma separated list of names as a string. Supported strings:

Note that if you are using class names, the format is always the same: [str]icon-- + icon set prefix + [str]-- + icon name, regardless of options.

Safelist or HTML

Unfortunately, listing icon names in plugin parameter is not enough. Tailwind CSS needs to see those class names used somewhere, or it ignores CSS generated by plugin. So you need to add class names to HTML that is scanned by Tailwind CSS or add it to [prop]safelist property of config, like other class names.

This could be a hassle, so that's one of the reasons why this plugin is listed only in advanced usage. Tailwind CSS developers aren't making things easy for plugin developers.

Options

The options parameter can be used to customise class names.

It has the following properties:

Multiple instances

You can add plugin to the plugin list in Tailwind CSS config multiple times, with different options or different list of icons.

Usage

index

title: Iconify for Tailwind CSS
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "60k"
    value: "${counters.icons-short}"

Iconify for Tailwind CSS

Iconify plugin for Tailwind CSS makes it easy to use icons in Tailwind CSS.

You can use over 60,000 open source icons and custom icons with minimal code.

Plugins

There are separate plugins for Tailwind 3 and Tailwind 4.

Tailwind 3 plugin is also usable with Tailwind 4, but requires creating a configuration file.

Follow one of these links for documentation:

Usage

options

title: Options in Iconify for Tailwind CSS
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyInfo: '/docs/types/iconify-info.md'

Options for Tailwind CSS

This page was moved to [func]addDynamicIconSelectors() documentation.

Usage

customise

title: Customising icons in Iconify for Tailwind CSS
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyInfo: '/docs/types/iconify-info.md'
functions:
  addDynamicIconSelectors: './index.md'

Customising icons in Iconify for Tailwind CSS

This documentation covers [prop]customise option for [func]addDynamicIconSelectors plugin.

Customise callback

Option [prop]customise allows you to change content of icons.

What is it for?

...and so on. You have full control over SVG content.

Usage

[prop]customise option is a function, which has 3 parameters:

Function should return modified content. If there is nothing to modify, it should return original [prop]content value.

Example

Example of using [prop]customise option to change [prop]stroke-width in Tabler icons:

addDynamicIconSelectors({
    // Change prefix
    // Thin icons will be used as <span class="icon-thin-[tabler--app-window]"></span>
    // and <span class="icon-[tabler--app-window]"></span> will still have default 2px stroke
    prefix: 'icon-thin',
    // Customise content
    customise: (content, name, prefix) => {
        switch (prefix) {
            case 'tabler':
                return content.replaceAll('stroke-width="2"', 'stroke-width="1"');
        }
        return content;
    }
})
Usage

icon-sets

title: Custom icon sets in Iconify for Tailwind CSS
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyInfo: '/docs/types/iconify-info.md'
functions:
  addDynamicIconSelectors: './index.md'

Custom icon sets in Iconify for Tailwind CSS

This documentation covers [prop]iconSets option for [func]addDynamicIconSelectors plugin.

iconSets option

Option [prop]iconSets allows you to use custom icon sets with plugin.

Option is an object, where key is an icon set prefix, and value is one of the following:

Make sure icon set includes [prop]info property with [prop]palette set. Plugin uses this to tell if an icon set contains icons with hardcoded palette or monotone icons. Mixed icon sets cannot be used. See [type]IconifyInfo type.

addDynamicIconSelectors({
	iconSets: {
		test: './icon-sets/test.json',
	},
});
Usage

index

title: Using Iconify for Tailwind CSS
types:
  IconifyJSON: "/docs/types/iconify-json.md"
  IconifyInfo: "/docs/types/iconify-info.md"
functions:
  addIconSelectors: "../iconify/index.md"

Using Iconify plugin for Tailwind CSS

Iconify plugin for Tailwind CSS package has several plugins. This documentation covers [func]addDynamicIconSelectors plugin.

This plugin for Tailwind 3, which can also be used with Tailwind 4 but requires creating a config file.

For newer Tailwind 4 plugin, see Tailwind 4 plugin documentation.

The Difference

What makes this plugin different from [func]addIconSelectors()?

It is easier to use.

Downsides:

HTML

To use icons in HTML, all you have to do is create [tag]span element with a class name that contains icon name.

Syntax of class names is this: [str]icon-[{prefix}--{name}], where [str]{prefix} is icon set prefix, [str]{name} is icon name.

Examples:

<span class="icon-[ph--alarm-duotone]"></span>
<span class="icon-[fluent-emoji-flat--alarm-clock]"></span>
<span class="icon-[carbon--edit-off]"></span>

Make sure prefix and icon name are separated with two hyphens: [str]--.

Why such a complex syntax? It is because of Tailwind CSS limitations. It can handle dynamic class names only if they are created in format [str]rule-[value].

Usage

To add plugin to Tailwind CSS, you need to open [file]tailwind.config.js, import [func]addDynamicIconSelectors from [npm]@iconify/tailwind and add it to a list of plugins.

Basic usage

const { addDynamicIconSelectors } = require("@iconify/tailwind");

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/*.html"],
  plugins: [
    // Iconify plugin
    addDynamicIconSelectors(),
  ],
};

Color

To change icon color, change text color. See how monotone icons work in CSS.

Size

See icon size documentation.

Advanced usage

Plugin accepts options to customise plugin behavior.

If you need to, you can create several instances of plugin with different options.

You must use a different value for [prop]prefix option for each plugin instance!

const { addDynamicIconSelectors } = require("@iconify/tailwind");

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/*.html"],
  plugins: [
    // Iconify plugin
    addDynamicIconSelectors({
      // Prefix for selectors, must be different for each addDynamicIconSelectors()
      prefix: "icon",
      // Removes redundant rules
      overrideOnly: false,
      // Icon height, 0 to disable size
      scale: 1,
      // Custom icon sets
      iconSets: {},
      // Callback to customise icons (such as change stroke-width, color, etc...).
      // First param is content, second is icon name, third is icon set prefix.
      // Function should return modified content.
      customise: (content, name, prefix) => content,
    }),
  ],
};

Options

Plugin options:

Default values for all options are shown in code sample above.

prefix

Option [prop]prefix sets prefix for dynamic class names.

Default value is [str]icon.

For example, if you set it to [str]icon-hover, like in a code sample above, you can use icons as [str]icon-hover-[mdi-light--home].

Value must not include [str]- at the end. Class names will always have [str]- added after prefix. That's how Tailwind CSS dynamic class names work.

You can use multiple instances of plugin with different [prop]prefix values to support different configuration options, like in the example below.

overrideOnly

If enabled, generated CSS will include only rules that override icons.

For example, with configuration in code example above, plugin will generate the following CSS for [str]icon-hover-[mdi-light--arrow-right]:

.icon-hover-\[mdi-light--arrow-right\] {
  --svg: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cpath fill='black' d='M4 12h12.25L11 6.75l.66-.75l6.5 6.5l-6.5 6.5l-.66-.75L16.25 13H4v-1Z'/%3E%3C/svg%3E");
}

This can be used in combination with default selectors to swap icon on hover without duplicating CSS:

src: usage/tailwind/override.js
hint: "tailwind.config.js"
extra:
  - src: usage/tailwind/override.html
    title: "Usage example:"

iconSets

With [prop]iconSets you can use custom files for icon sets.

See custom icon sets documentation.

scale

See icon size documentation.

Customise option

Customise option can be used to customise icons.

You can change icon color, stroke width, animation duration and so on.

See customise option documentation for details and usage examples.

Issues

If everything is done correctly, icons should work.

Possible issues:

Errors when building CSS

If an icon set is missing or icon is missing, the plugin will throw errors.

See error message. If the plugin cannot find an icon set, install dependency. If the plugin cannot find icon, you are using the wrong icon name.

Selectors do not work

You have added class names, built your CSS, but icons do not work?

First, make sure the class name is correct. If it is correct, most likely Tailwind CSS is not seeing your class names. If you are familiar with Tailwind CSS, the process of fixing it is exactly the same as any other missing class name:

Multiple instances

You can add plugin to the plugin list in Tailwind CSS config multiple times, with different options.

Each [func]addDynamicIconSelectors() entry in the plugin list should have different [prop]prefix option to avoid conflicts. The default value for [prop]prefix is [str]icon.

Usage

size

title: Changing icon size and color in Iconify for Tailwind CSS
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyInfo: '/docs/types/iconify-info.md'
functions:
  addDynamicIconSelectors: './index.md'

Changing icon size in Iconify for Tailwind CSS

This documentation explains how to change icon size and color for [func]addDynamicIconSelectors plugin.

Icon size

By default, icons are rendered with [num]1em height.

Width is set automatically, using icon's width/height ratio. Though the vast majority of icons are square, so usually width is the same as height.

To change icon size, you can change font size:

<span class="icon-[mdi-light--home] text-2xl"></span>

Additionally, you can:

Scaling icon

Option [prop]scale changes default icon size from [num]1em.

The following configuration

addDynamicIconSelectors({
    scale: 1.2,
})

changes default height to [num]1.2em.

You can use font size to further resize icons, like in the example above, but icons will be 1.2 times bigger.

Custom size {#custom}

To use width and height to resize icons, you need to set [prop]scale to [num]0:

addDynamicIconSelectors({
    scale: 0,
})

If you do this, icons will not have width and height, so you must set size to each icon:

<span class="icon-[mdi-light--home] h-12 w-12"></span>

Multiple sizes

What if you want to use [num]1em icons, icons without size and icons with fixed size in pixels in the same project?

You can use multiple instances of plugin with different settings and different selectors:

plugins: [
    // Default options, 1em height
    addDynamicIconSelectors(),
    // No size
    addDynamicIconSelectors({
        // Change prefix
        prefix: 'icon-nosize',
        // Disable width and height 
        scale: 0,
    })
]
<p>
  Icon with 1em size: 
  <span class="icon-[mdi-light--home]"></span>
</p>
<p>
  Icon without size (using custom width/height): 
  <span class="icon-nosize-[mdi-light--home] h-12 w-12"></span>
</p>

Note that [prop]prefix option in plugin config does not have [str]- at the end, but it does in HTML. This is due to Tailwind CSS requirements for dynamic selectors. Make sure to not forget [str]- in HTML.

Usage

customise

title: Customising icons in Iconify for Tailwind CSS
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyInfo: '/docs/types/iconify-info.md'
functions:
  addIconSelectors: './index.md'

Customising icons in Iconify for Tailwind CSS

This documentation covers [prop]customise option for [func]addIconSelectors plugin.

Customise callback

Option [prop]customise allows you to change content of icons.

What is it for?

...and so on. You have full control over SVG content.

Usage

[prop]customise option is a function, which has 3 parameters:

Function should return modified content. If there is nothing to modify, it should return original [prop]content value.

Example

Example of using [prop]customise option to change [prop]stroke-width in Tabler icons:

addIconSelectors({
    prefixes: ['tabler'],
    customise: (content, name, prefix) => {
        switch (prefix) {
            case 'tabler':
                return content.replaceAll('stroke-width="2"', 'stroke-width="1.5"');
        }
        return content;
    }
})

Conflicts

If you also have a [prop]customise option used in entry in [prop]prefixes option, that callback has a priority and main [prop]customise will not be used for that icon set.

Usage

index

title: Using Iconify for Tailwind CSS
types:
  IconifyJSON: "/docs/types/iconify-json.md"
  IconifyInfo: "/docs/types/iconify-info.md"
functions:
  addDynamicIconSelectors: "../dynamic/index.md"

Using Iconify plugin for Tailwind CSS

Iconify plugin for Tailwind CSS package has several plugins. This documentation covers [func]addIconSelectors plugin.

This plugin for Tailwind 3, which can also be used with Tailwind 4 but requires creating a config file.

For newer Tailwind 4 plugin, see Tailwind 4 plugin documentation.

The Difference

What makes this plugin different from [func]addDynamicIconSelectors()?

Downsides:

HTML

To add icon to HTML, all you have to do is create a [tag]span element with two class names:

Examples:

<span class="iconify ph--alarm-duotone"></span>
<span class="iconify-color fluent-emoji-flat--alarm-clock"></span>
<span class="iconify carbon--edit-off"></span>

Why two class names? To reduce duplication and make CSS much smaller. One class has only icon data, another reusable class tells the browser how to render that icon data.

Icon class names

Each rendered icon shares most of its rules with other icons. By splitting those rules into separate classes, CSS becomes much smaller.

Icon name selector

Icon name selector sets icon data. Syntax is [str]{prefix}--{name}, where [str]{prefix} is icon set prefix, [str]{name} is icon name. Syntax can be easily changed in plugin options.

CSS generated by plugin for an icon:

.mdi-light--home {
  --svg: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cpath fill='black' d='m16 8.41l-4.5-4.5L4.41 11H6v8h3v-6h5v6h3v-8h1.59L17 9.41V6h-1zM2 12l9.5-9.5L15 6V5h3v4l3 3h-3v8h-5v-6h-3v6H5v-8z'/%3E%3C/svg%3E");
}

Iconify selector

Icon can be rendered as either background image or mask image.

Mask image renders icon in text color. See how monotone icons work in CSS. To render icon as a mask image, add [str]iconify selector.

Background image renders icon in color that is set in icon (should be used for things like emojis that have hardcoded palette). To render icon as a background image, add [str]iconify-color selector.

Selectors can be easily changed in plugin options.

CSS generated by plugin for reusable selectors:

.iconify {
  display: inline-block;
  width: 1em;
  height: 1em;
  background-color: currentColor;
  -webkit-mask-image: var(--svg);
  mask-image: var(--svg);
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no-repeat;
  -webkit-mask-size: 100% 100%;
  mask-size: 100% 100%;
}

.iconify-color {
  display: inline-block;
  width: 1em;
  height: 1em;
  background-image: var(--svg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

Color and size

To change icon color and size, use color and size class names like you would for any text:

<span class="iconify ph--alarm-duotone text-red-600 text-2xl"></span>

You can also resize an icon using width and height:

<span class="iconify-color twemoji--cat-face w-12 h-12"></span>

Make sure width and height are the same because some browsers (Safari) fail to keep proportions when using SVG as a mask image.

If you set option [prop]square to false, icons are not square, and you are using custom width and height classes, make sure width/height ratio matches icon's width/height ratio.

See size documentation.

Usage

To add plugin to Tailwind CSS, you need to open [file]tailwind.config.js, import [func]addIconSelectors from [npm]@iconify/tailwind and add it to a list of plugins.

Basic usage

const { addIconSelectors } = require("@iconify/tailwind");

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/*.html"],
  plugins: [
    // Iconify plugin, requires writing list of icon sets to load
    addIconSelectors(["mdi", "mdi-light"]),
  ],
};

Parameter to [func]addIconSelectors is an array of icon sets you want to use.

To avoid generating too many icons, which would take a huge amount of time, you need to tell plugin which icon sets you want to use.

Entry can be an icon set prefix or a custom icon set.

Size and color

See size and color documentation.

Advanced usage

The plugin also accepts an object with options as parameter.

The only required option is [prop]prefixes, which is a list of prefixes, same as an array in the example above.

const { addIconSelectors } = require("@iconify/tailwind");

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/*.html"],
  plugins: [
    // Iconify plugin, requires writing list of icon sets to load
    addIconSelectors({
      // List of prefixes, required
      prefixes: ["mdi", "mdi-light"],

      // All other properties below are optional. This example shows default values.
      // Mask and background selectors
      maskSelector: ".iconify-color",
      backgroundSelector: ".iconify",
      // Icon selector, must have "{prefix}" and "{name}" in it
      iconSelector: ".{prefix}--{name}",
      // Variable name to use for icon data
      varName: "svg",
      // Scale icons, which sets width/height in background/mask selectors
      scale: 1,
      // Make icons square
      square: true,
      // Extra rules to add to mask and background selectors
      extraMaskRules: {},
      extraBackgroundRules: {},
      // Callback to customise icons (such as change stroke-width, color, etc...).
      // First param is content, second is icon name, third is icon set prefix.
      // Function should return modified content.
      customise: (content, name, prefix) => content,
    }),
  ],
};

Options

Plugin options:

Default values for all options, except [prop]prefixes are shown in code sample above. The default value for [prop]prefixes is an empty array.

Prefixes list

This plugin requires setting a list of icon sets you want to use, set as either the only parameter to plugin or as [prop]prefixes property in options.

You can use it to:

See prefixes option documentation for details and usage examples.

Customise option

Customise option can be used to customise icons.

You can change icon color, stroke width, animation duration and so on.

See customise option documentation for details and usage examples.

Selectors

Options [prop]maskSelector and [prop]backgroundSelector can be used to customise selectors used for background and mask.

See selectors options documentation for details and usage examples.

Issues

If everything is done correctly, icons should work.

Possible issues:

Errors when building CSS

If an icon set is missing or icon is missing, the plugin will throw errors.

See error message. If the plugin cannot find an icon set, install dependency. If the plugin cannot find icon, you are using the wrong icon name.

Selectors do not work

You have added class names, built your CSS, but icons do not work?

First, make sure the class name is correct. If it is correct, most likely Tailwind CSS is not seeing your class names. If you are familiar with Tailwind CSS, the process of fixing it is exactly the same as any other missing class name:

Usage

prefixes

title: Selecting icon sets in Iconify for Tailwind CSS
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyInfo: '/docs/types/iconify-info.md'
functions:
  addIconSelectors: './index.md'

Selecting icon sets in Iconify for Tailwind CSS

This documentation covers [prop]prefixes option for [func]addIconSelectors plugin.

Prefixes list

[func]addIconSelectors() plugin requires setting a list of icon sets you want to use, set as either the only parameter to plugin or as [prop]prefixes property in options.

Why is it needed?

Value of prefixes list is an array, each entry can be:

If you use a string with icon set prefix, all icons in icon set will be parsed without any changes.

[type]IconSetOptions object gives you more control over icons, allowing you to filter icons, customise icons and load custom icon sets.

IconSetOptions

Object [type]IconSetOptions has the following properties:

Either [prop]prefix or [prop]source must be set. If both are set, the icon set is loaded from [prop]source, but prefix is set to value of [prop]prefix.

Source

Property [prop]source of [type]IconSetOptions can be:

Icons

Property [prop]icons of [type]IconSetOptions can be used to filter icons in the loaded icon set.

By filtering unused icons, you can improve parsing time, thus making the build process faster.

Customise

Property [prop]customise of [type]IconSetOptions can be used to customise icons. For example, to change [prop]stroke-width, change certain color in icons with color, change animation duration in animated icons and so on.

Callback has two parameters:

Callback should return new content. If icon is not modified, it should return value passed in [prop]content property.

Examples

Examples of using [prop]prefixes option to load custom icon sets and customise icons:

addIconSelectors({
    prefixes: [
        {
            // Change stroke width in Tabler icons
            prefix: 'tabler',
            customise: (content) =>
                content.replaceAll('stroke-width="2"', 'stroke-width="1.5"'),
        },
        {
            // Change color in face emojis from Twitter, also rename icon set
            
            // Change icon set prefix by setting 'prefix' property
            prefix: 'twemoji-red',
            
            // Resolve location of icon set from '@iconify-json/twemoji' package 
            // Also below is the same code, using '@iconify/json' package
            source: require.resolve('@iconify-json/twemoji/icons.json'),
            // source: require.resolve('@iconify/json/json/twemoji.json'),
            
            // Filter only icons that contain 'face' to improve plugin performance
            icons: (name) => name.includes('face'),
            
            // Change color
            customise: (content, name) => content.replaceAll('#ffcc4d', '#ff9667'),
        },
        {
            // Load custom icon set. It can be pre-generated using Iconify Tools
            prefix: 'custom',
            source: 'data/custom.json',
            
            // Example of using Iconify Tools icon set as source. Assumes that customIconSet is an IconSet class instance. 
            // source: customIconSet.export(),
        },
    ],
})
Usage

selectors

title: Selectors in Iconify for Tailwind CSS
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyInfo: '/docs/types/iconify-info.md'
functions:
  addIconSelectors: './index.md'

Selectors in Iconify for Tailwind CSS

This documentation covers options that change selectors for [func]addIconSelectors plugin.

Options

There are several selectors set by plugin:

To render an icon, you need to use icon selector (which provides icon data) and either background or mask selector (which renders that icon).

You can customise all of them.

Why would you want to do that?

Mask and background image

Mask and background image selectors must be used in each icon together with icon name selector. These selectors contain all rules needed to render icon as mask or background image.

To customise mask or background image selectors, use the following options:

Set value to an empty string to disable it.

Why would you want to disable it? It can be useful if classes are already set somewhere else, such as another instance of plugin, or you are not using background or mask mode.

Extra rules

You can also add CSS rules for background and mask selectors by using [prop]extraBackgroundRules and [prop]extraMaskRules options.

That can be used to change dimensions, display mode or add vertical alignment.

Icon selector

Icon selector gives you control over icon name. To change it, change option [prop]iconSelector.

Value must include:

Default value is [str].{prefix}--{name}.

Examples

The following configuration changes syntax to syntax used by UnoCSS:

However, be aware that you still must have a background or a mask selector for each icon, which UnoCSS does not use.

addIconSelectors({
    iconSelector: '.i-{prefix}-{name}',
    // UnoCSS uses scale 1.2 by default
    scale: 1.2
})
<span class="iconify i-mdi-light-home"></span>

The following configuration will create several instances of plugin with different options:

plugins: [
    addIconSelectors(['mdi-light']),
    addIconSelectors({
        // Change selectors to avoid conflicts
        maskSelector: '.icon',
        backgroundSelector: '.icon-color',
        // Disable width and height 
        scale: 0,
        // Not using 'prefixes' because icons are already set in previous instance
        // Yes, you can mix selectors from different instances of plugin: background or mask from one, 
        // icon from another, but only as long as `varName` option is the same (or not customised).
        // Since icons used in example below are identical, no need to re-parse them.
    }),
    addIconSelectors({
        // Align icon below baseline and set fixed size
        maskSelector: '.material-icon',
        extraMaskRules: {
            'vertical-align': '-0.125em',
            'width': '24px',
            'height': '24px',
        },
        // Not using background selector for this demo - demo uses monotone icons only
        backgroundSelector: '',
    })
]
<p>
  Icon with 1em size: 
  <span class="iconify mdi-light--home"></span>
</p>
<p>
  Icon without size (using custom width/height): 
  <span class="icon mdi-light--home h-12 w-12"></span>
</p>
<p>
  24px icon aligned to bottom: 
  <span class="material-icon mdi-light--home"></span>
</p>
Usage

size-color

title: Changing icon size and color in Iconify for Tailwind CSS
types:
  IconifyJSON: '/docs/types/iconify-json.md'
  IconifyInfo: '/docs/types/iconify-info.md'
functions:
  addIconSelectors: './index.md'

Changing icon size and color in Iconify for Tailwind CSS

This documentation explains how to change icon size and color for [func]addIconSelectors plugin.

Icon color

There are two types of icons:

See how monotone icons work in CSS (html syntax in linked tutorial is different - tutorial is not specific to this plugin).

Monotone icons

To change the color of monotone icons, render them as mask images and change text color:

<span class="iconify mdi-light--home text-blue-600"></span>

Icons with palette

Icons with hardcoded palette aren't designed to be customisable. However, [func]addIconSelectors plugin gives you option to change color via [prop]customise option.

For example, this code will change yellow background in Twitter emojis with red:

addIconSelectors({
    prefixes: [
        // Render 'twemoji' icon set
        'twemoji',
        // Render 'twemoji' as 'twemoji-red' with custom color changes 
        {
            // Change icon set prefix by setting 'prefix' property
            prefix: 'twemoji-red',
            
            // Resolve location of icon set from '@iconify-json/twemoji' package 
            // Also below is the same code, using '@iconify/json' package
            source: require.resolve('@iconify-json/twemoji/icons.json'),
            // source: require.resolve('@iconify/json/json/twemoji.json'),
            
            // Filter only icons that contain 'face' to improve plugin performance
            icons: (name) => name.includes('face'),
            
            // Change color
            customise: (content, name) => content.replaceAll('#ffcc4d', '#ff9667'),
        },
    ],
})

Then you can use both original and customised icons:

<span class="iconify-color twemoji--winking-face"></span>
<span class="iconify-color twemoji-red--winking-face"></span>

See customise option documentation for details and usage examples.

Also see prefixes option documentation for explanation of how the configuration above works.

Icon size

By default, icons are rendered as [num]1em x [num]1em square.

To change icon size, you can change font size:

<span class="iconify mdi-light--home text-2xl"></span>

Because common selectors, which contain size, are treated as Tailwind components, you can also set width/height to resize icon:

<span class="iconify mdi-light--home w-12 h-12"></span>

Make sure width and height are identical (see [prop]square option below). Some browsers (Safari) fail to keep proportions when using SVG as a mask image, so using different width and height values might result in unexpected user experience for some users.

Additionally, you can change default size by using [prop]scale option.

Non-square icons

By default, all icons are rendered as square icons. This makes it easy to resize icons.

However, if you want to render non-square icons as is, you can disable this behavior by changing option [prop]square to false:

addIconSelectors({
    prefixes: ['fa6-regular'],
    square: false,
})

However, be aware that this might make resizing icon a bit more complex. If you are setting [prop]width and [prop]height, make sure width/height ratio matches icon's ratio.

Scaling icon

Option [prop]scale changes default icon size from [num]1em.

The following configuration

addIconSelectors({
    prefixes: ['mdi-light'],
    scale: 1.2,
})

changes default size to [num]1.2em x [num]1.2em square.

You can use font size to further resize icons, like in the example above, but icons will be 1.2 times bigger.

Fixed size

If you want to set default icon size to a fixed size in pixels, such as [num]24 to render icons that are designed for [num]24 x [num]24, you can set width and height in pixels using [prop]extraMaskRules or [prop]extraBackgroundRules options:

addIconSelectors({
    maskSelector: '.material-icon',
    extraMaskRules: {
        'width': '24px',
        'height': '24px',
    },
    backgroundSelector: '.material-icon-color',
    extraBackgroundRules: {
        'width': '24px',
        'height': '24px',
    },
})

Multiple sizes

What if you want to use [num]1em icons, icons without size and icons with fixed size in pixels in the same project?

You can use multiple instances of plugin with different settings and different selectors:

plugins: [
    // Default options, 1em size
    addIconSelectors(['mdi-light']),
    // Fixed size
    addIconSelectors({
        // Set fixed size
        maskSelector: '.material-icon',
        extraMaskRules: {
            'width': '24px',
            'height': '24px',
        },
        // Not using background selector for this demo - demo uses monotone icons only
        backgroundSelector: '',
    }),
]
<p>
  Icon with 1em size: 
  <span class="iconify mdi-light--home"></span>
</p>
<p>
  Using custom width/height: 
  <span class="iconify mdi-light--home h-12 w-12"></span>
</p>
<p>
  24px icon:
  <span class="material-icon mdi-light--home"></span>
</p>

Because icon data is identical in all instances of plugin, there is no need to change icon selector and the [prop]prefixes option needs to be used only once. This reduces duplication and makes parsing faster.

Usage

index

title: Iconify for Tailwind CSS version 3
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "60k"
    value: "${counters.icons-short}"
functions:
  addDynamicIconSelectors: "../dynamic/index.md"
  addIconSelectors: "../iconify/index.md"

Iconify for Tailwind CSS

Iconify plugin for Tailwind CSS makes it easy to use icons in Tailwind CSS.

You can use over 60,000 open source icons and custom icons with minimal code.

Tailwind CSS version

This documentation covers plugins for Tailwind 3.

For a newer Tailwind 4 plugin, see Tailwind 4 plugin documentation.

However, Tailwind 3 plugins can be used with Tailwind 4 too, but you need to create a configuration file.

Plugins

There are several plugins available, they use different syntax, have different options.

There are 2 main plugins:

Plugins use different syntax, have different options.

For example, here is syntax to use icon [icon]mdi-light:home in HTML:

src: usage/tailwind/syntax-iconify.html
hint: "Usage with addDynamicIconSelectors"
src: usage/tailwind/syntax-iconify2.html
hint: "Usage with addIconSelectors"

Installation

To install plugins, add [npm]@iconify/tailwind as dev dependency:

npm i -D @iconify/tailwind

Then you need to configure it.

Tailwind 3 configuration

For Tailwind CSS 3, open [file]tailwind.config.js, import [func]addIconSelectors (main plugin) or [func]addDynamicIconSelectors (dynamic selectors) from [npm]@iconify/tailwind and add it to a list of plugins.

Example [file]tailwind.config.js with [func]addIconSelectors() plugin:

const { addIconSelectors } = require("@iconify/tailwind");

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/*.html"],
  plugins: [
    // Iconify plugin for clean selectors, requires writing a list of icon sets to load
    // Icons usage in HTML:
    //  <span class="iconify mdi-light--home"></span>
    //  <span class="iconify-color vscode-icons--file-type-tailwind"></span>
    addIconSelectors(["mdi-light", "vscode-icons"]),
  ],
};

Example [file]tailwind.config.js with [func]addDynamicIconSelectors() plugin:

const { addDynamicIconSelectors } = require("@iconify/tailwind");

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/*.html"],
  plugins: [
    // Iconify plugin for dynamic selectors, configuration is not required
    // Icons usage in HTML:
    //  <span class="i-[mdi-light--home]"></span>
    addDynamicIconSelectors(),
  ],
};

Tailwind 4 config

For Tailwind 4, you need to create a new file, for example, [file]icons.mjs with configuration:

import { addDynamicIconSelectors } from "@iconify/tailwind";

export default addDynamicIconSelectors();

Then in your CSS file import that plugin:

@plugin './icons.mjs';

All code samples in documentation are for Tailwind CSS 3.

Tailwind CSS 4 configuration is similar, except that instead of adding plugin to [prop]plugins property of Tailwind configuration, you need to export it as a default export.

This requires basic understanding of how modules and exports work.

Icon sets

Plugin does not include icons. You need to add icon sets you want to use.

To add all open source icon sets, add [npm]@iconify/json as dev dependency:

npm i -D @iconify/json

You can also install only icon sets that you want to use by installing [npm]@iconify-json/{prefix} dependencies (where [str]{prefix} is icon set prefix), such as [npm]@iconify-json/mdi-light.

See icon data documentation.

Custom icon sets

Plugins also work with custom icon sets, see detailed documentation below.

Usage

For more details, see documentation for each plugin:

Usage

custom-icons

title: Custom icons in Iconify for Tailwind CSS
types:
  IconifyJSON: "/docs/types/iconify-json.md"

Custom icons in Iconify for Tailwind CSS

This documentation explains how to use Iconify plugin for Tailwind CSS 4 with custom icons.

Loader options

There are two methods of loading icon sets:

Syntax is similar:

@plugin "@iconify/tailwind4" {
  icon-sets: from-json(test, "./icon-sets/test.json"), from-folder(test2, "./icon-sets/svgs");
}

Add option [prop]icon-sets to plugin config in CSS, with comma separated sets of options.

Loading from JSON file

Loading from JSON file is faster because there is no clean up to do, so if you can, load icon sets from a JSON file.

File must be in [type]IconifyJSON format, which can be created with Iconify Tools.

To add an icon set to config, add [func]from-json() function to [prop]icon-sets option, with two values:

Loading from folder

Loading from folder makes it easy to use existing icons without pre-parsing them.

To add a folder with icons to config, add [func]from-folder() function to [prop]icon-sets option, with two values:

You can load icons from multiple folders by adding multiple entries with different prefixes to [prop]icon-sets option.

Clean up

Icons loaded from folder are cleaned up and optimised.

If you do not want this, pre-parse icons, export them as [type]IconifyJSON file and load .json file instead.

How icons are handled:

Examples

Examples of configuration:

@plugin "@iconify/tailwind4" {
  icon-sets: from-json(test, "./icon-sets/test.json"), from-folder(test2, "./assets/svg");
}

@plugin "@iconify/tailwind4" {
  prefix: "square-icon";
  square: true;
  icon-sets: from-folder(test3, "./assets/svg");
}
Usage

index

title: Iconify for Tailwind CSS 4
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "60k"
    value: "${counters.icons-short}"

Iconify for Tailwind CSS

Iconify plugin for Tailwind CSS makes it easy to use icons in Tailwind CSS.

You can use over 60,000 open source icons and custom icons with minimal code.

Plugins

This documentation covers plugin for Tailwind 4.

For an older Tailwind 3 plugin, see Tailwind 3 plugin documentation. It works with Tailwind 4 too, currently has more options than new plugin, but requires creating a config file.

Installation

To install plugin, add [npm]@iconify/tailwind4 as dev dependency:

npm i -D @iconify/tailwind4

Plugin does not include icons. You need to add icon sets you want to use.

To add all open source icon sets, add [npm]@iconify/json as dev dependency:

npm i -D @iconify/json

You can also install only icon sets that you want to use by installing [npm]@iconify-json/{prefix} dependencies (where [str]{prefix} is icon set prefix), such as [npm]@iconify-json/mdi-light.

See icon data documentation.

Basic usage

Add this to your CSS:

@plugin "@iconify/tailwind4";

To use icons, add dynamic selector for icon, such as

src: usage/tailwind/syntax-iconify.html

Browse or search icons at Iconify icon sets website, click icon you want to use, in code options select "CSS" -> "Tailwind CSS" and copy code.

Options

Plugin supports several options:

Example of configuration:

@plugin "@iconify/tailwind4" {
  prefix: "iconify";
  scale: 1.2;
}

Custom icons

Plugin supports custom icons and icon sets via [prop]icon-sets option.

See custom icons documentation.

Clean selectors

There are actually 2 plugins in one:

Plugin for clean selectors uses a cleaner syntax for icons, but requires adding a configuration:

src: usage/tailwind/syntax-iconify2.html

What configuration is required?

You need to specify what icon sets you want to render.

This is done by setting list of prefixes:

@plugin "@iconify/tailwind4" {
  prefixes: mdi-light, vscode-icons;
}

Extra class name

Each icon has 2 class names:

All icons share same rules, except for image URL.

To avoid duplication, common rules were split into utility classes. Additionally, this allows you to choose how icon is rendered:

Why is config required? {#config-explanation}

Why is it needed?

Tailwind CSS works by finding class names in your code and rendering CSS for those class names.

When working with dynamic class names, such as [str]icon-[mdi-light--home], Tailwind CSS finds all such class names and passes them to a plugin to generate CSS. That means plugin knows which icons are used and loads only required icons.

However, when using plain class names, such as [str]mdi-light--home, Tailwind CSS requires a plugin to generate CSS for all possible class names first, before finding class names in your project, then it removes unused class names. That means plugin must generate CSS for every single icon that might exist.

Generating CSS for every single icon is not a fast process. With over 60,000 icons available, it might take a lot of time. Then Tailwind CSS keeps it all in memory, which might cause Tailwind CSS to run out of memory. To avoid that, you must specify list of icon sets you want to use.

Usage

size-color

title: Changing icon size and color in Iconify for Tailwind CSS
types:
  IconifyJSON: "/docs/types/iconify-json.md"
  IconifyInfo: "/docs/types/iconify-info.md"
functions:
  addIconSelectors: "./index.md"

Changing icon size and color in Iconify for Tailwind CSS

This documentation explains how to change icon size and color for Iconify plugin for Tailwind CSS 4.

Icon color

There are two types of icons:

See how monotone icons work in CSS (html syntax in linked tutorial is different - tutorial is not specific to this plugin).

Dynamic selectors

When using dynamic selectors plugin, it automatically sets rendering mode for each icon. You cannot control it.

For example, [str]icon-[mdi-light--home] will be rendered as a mask image because that icon is a monotone icon.

Clean selectors

When using clean selectors, you need to specify how you want icon to be rendered by adding either:

Setting a default rendering mode

Optionally you can set one of these modes as default. The following code allows you to skip adding the [str]iconify class when using any icon from the mdi icon set.

[class*="mdi--"]:not([class*="iconify-color"]) {
    @apply iconify;
  }

Monotone icons

To change the color of monotone icons, render them as mask images and change text color:

<span class="iconify mdi-light--home text-blue-600"></span>

Icons with palette

Icons with hardcoded palette currently cannot be customised.

<span class="iconify-color twemoji--winking-face"></span>

Custom colors are possible though if you use plugin for Tailwind CSS 3. It uses JavaScript for configuration, which opens a lot more possibilities than CSS configuration Tailwind CSS 4.

Icon size

By default, icons are rendered as [num]1em x [num]1em square.

To change icon size, you can change font size:

<span class="iconify mdi-light--home text-2xl"></span>

Because common selectors, which contain size, are treated as Tailwind components, you can also set width/height to resize icon:

<span class="iconify mdi-light--home w-12 h-12"></span>

Make sure width and height are identical (see [prop]square option below). Some browsers (Safari) fail to keep proportions when using SVG as a mask image, so using different width and height values might result in unexpected user experience for some users.

Additionally, you can change default size by using [prop]scale option.

Non-square icons

By default, all icons are rendered as square icons. This makes it easy to resize icons.

However, if you want to render non-square icons as is, you can disable this behavior by changing option [prop]square to false:

@plugin "@iconify/tailwind4" {
  square: false;
}

However, be aware that this might make resizing icon a bit more complex. If you are setting [prop]width and [prop]height, make sure width/height ratio matches icon's ratio.

Scaling icon

Option [prop]scale changes default icon size from [num]1em.

The following configuration

@plugin "@iconify/tailwind4" {
  scale: 1.2;
}

changes default size to [num]1.2em x [num]1.2em square.

You can use font size to further resize icons, like in the example above, but icons will be 1.2 times bigger.

Usage

index

title: Iconify in UnoCSS
replacements:
  - code: '60,000'
    value: '${counters.icons}'
  - code: '60k'
    value: '${counters.icons-short}'
types:
  IconifyIcon: '/docs/types/iconify-icon.md'

Icons with UnoCSS

If you are using UnoCSS, you can easily use over 60,000 open source icons and custom icons with minimal code.

Among other features, UnoCSS has [npm]@unocss/preset-icons package that dynamically generates icons. It uses icon data from Iconify.

Usage

To use icons with UnoCSS, add [npm]@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: [str]i- + icon set prefix + [str]- + 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 [num]1.2em.

You can change that by changing [prop]scale option.

If you want to change [prop]width and [prop]height separately or make icon square, you can use [prop]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 [file]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 [prop]customize option.

Option [prop]customize is part of [prop]customizations option, it is a function has 3 parameters:

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 [prop]width, [prop]height, [prop]left and [prop]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 [js]console.log(data) to see icon data.

Usage

index

title: Generate CSS for icons with Iconify Utils
replacements:
  - code: '60,000'
    value: '${counters.icons}'
  - code: '60k'
    value: '${counters.icons-short}'
functions:
  getIconsCSS: '/docs/libraries/utils/get-icons-css.md'
  getIconCSS: '/docs/libraries/utils/get-icon-css.md'
  getIconsContentCSS: '/docs/libraries/utils/get-icons-content-css.md'
  getIconContentCSS: '/docs/libraries/utils/get-icon-content-css.md'

Generate CSS for icons with Iconify Utils

This method requires a bit of coding, using Node.js.

If you are not using Node.js or not comfortable with the code below, consider other methods of generating CSS for icons.

Node.js {#node}

If you do not have a Node.js app, you need to create one to generate CSS.

There are plenty of tutorials on how Node.js works, short version of steps:

Dependencies

You need to install two dependencies:

To install them, run

npm install --save-dev @iconify/utils @iconify/json

Functions

Iconify Utils has several functions that generate CSS for icons:

This tutorial shows how to use [func]getIconsCSS(), which fits most use cases.

Build script

The process of building CSS is simple:

src: usage/css-utils.js

Change the list of icons, location of [file].css file, run it to build CSS.

Usage

To use those icons in HTML, use [tag]span elements with two class names: class name for the icon set, class name for the icon.

<span class="icon--mdi-light icon--mdi-light--alert-circle"></span>

Options

There are options for [func]getIconsCSS() that you can use to customise generated CSS.

See getIconsCSS() documentation.

Usage

index

title: How to embed SVG in HTML
replacements:
  - code: '60,000'
    value: '${counters.icons}'
  - code: '60k'
    value: '${counters.icons-short}'
functions:
  iconToSVG: '/docs/libraries/utils/icon-to-svg.md'
  iconToHTML: '/docs/libraries/utils/icon-to-html.md'
  parseIconSet: '/docs/libraries/utils/parse-icon-set.md'
  getIconData: '/docs/libraries/utils/get-icon-data.md'

How to embed SVG in HTML

Using SVG in HTML requires embedding HTML in documents.

Skip to list of available tools if you want to skip long explanation of how it all works.

Advantages

There are advantages and disadvantages of using SVG in HTML over using SVG in CSS.

Advantages:

However, it also has big disadvantages:

Security

Additionally, there could be security concerns.

SVG from untrusted sources should never be embedded in HTML. SVG can include scripts, links to external resources (fonts, other images) that could potentially be used for tracking.

All icons in Iconify packages pass very strict validation, so they do not contain any potentially harmful content, such as scripts and external resources.

Usage

All you have to do is insert [tag]svg elements in your HTML wherever you want to use it.

<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24">
    <path fill="currentColor" d="M12 4a4 4 0 0 1 4 4a4 4 0 0 1-4 4a4 4 0 0 1-4-4a4 4 0 0 1 4-4m0 10c4.42 0 8 1.79 8 4v2H4v-2c0-2.21 3.58-4 8-4Z"/>
</svg>

External images

One possible solution to deep DOM tree and large document size is linking to external SVG files using [tag]img or [tag]picture tags.

However, it cannot be used for monotone icons. It is not possible to change color of external image without generating separate images for each used color. That makes external images unusable in the Iconify ecosystem.

A workaround is to use icons as external mask images in CSS. See how to use SVG in CSS.

Tools

How to get SVG to add to your documents?

Components

For many frameworks, there are components that handle embedding SVG in HTML:

Functions

Not using any frameworks, but want to automate the build process?

Iconify Utils offers easy to use functions that generate SVG.

See how to export SVG with Iconify Utils.

No code

If you do not want to use any components, you can get SVG at one of the following websites:

include usage/options/websites

Find icon you want to use, select it, copy SVG to clipboard, paste it to HTML.

Custom components

Want to build a custom component that generates SVG?

Currently, you'll need to use JavaScript for that. There are no usable libraries for other programming languages.

JavaScript

Iconify Utils package includes all functions you need. Process of generating SVG is simple:

Code samples that should help you:

Convert iconToSVG result to SVG {#icon-to-svg}

Function [func]iconToSVG() does not return full SVG, it returns attributes for [tag]svg element and contents.

This is done on purpose. Many frameworks, such as React, expect you to use the framework specific code to create elements.

So, for React, you need to create an element like this:

const data = iconToSVG(icon, {});

return React.createElement('svg', {
	// Mandatory attributes
	xmlns: 'http://www.w3.org/2000/svg',
	xmlnsXlink: 'http://www.w3.org/1999/xlink',
	// width, height, viewBox
	...data.attributes,
	// innerHTML
	dangerouslySetInnerHTML: {
		__html: data.body,
	},
});

For other frameworks that use native ways to create elements, use similar framework specific code.

If a framework does not have some way to set [prop]innerHTML, which is required to set contents of [tag]svg, this code cannot be used. You'll need to find a way to convert HTML string to tree of components.

If you want to create full [tag]svg element as string, you can use [func]iconToHTML() function to convert the result of [func]iconToSVG() to string:

const data = iconToSVG(icon, {});

return iconToHTML(data.body, data.attributes);

See Iconify Utils examples.

Usage

index

title: Astro Icon
replacements:
  - code: '60,000'
    value: '${counters.icons}'
  - code: '60k'
    value: '${counters.icons-short}'

Astro Icon and Astro Iconset

There are two components for Astro:

With those components, you can easily use over 60,000 open source icons and custom icons in Astro with minimal code.

Installation

When it comes to Iconify icons, both packages are very similar.

Astro Icon

Install [npm]astro-icon:

npm i -D astro-icon

Register the component in your astro.config.mjs:

import { defineConfig } from 'astro/config';
import icon from 'astro-icon';

export default defineConfig({
	integrations: [icon()],
});

Astro Iconset

Install [npm]astro-iconset:

npm i -D astro-iconset

Register the component in your astro.config.mjs:

import { defineConfig } from 'astro/config';
import icon from 'astro-iconset';

export default defineConfig({
	integrations: [icon()],
});

Usage

Usage is almost identical for both packages.

Astro Icon

Astro Icon can inline SVG directly in your HTML:

---
import { Icon } from 'astro-icon/components'
---

<Icon name="mdi:home" />

It can also generate SVG sprites.

See Astro Icon readme for more details.

Astro Iconset

Astro Icon can inline SVG directly in your HTML:

---
import { Icon } from "astro-iconset/components";
---

<Icon name="mdi:home" />

It can also generate SVG sprites.

See Astro Icon readme for more details.

Usage

index

title: SVG for icons without coding
replacements:
  - code: '60,000'
    value: '${counters.icons}'
  - code: '60k'
    value: '${counters.icons-short}'
  - code: '70 icon sets'
    value: '${counters.sets} icon sets'
  - code: '70 open source'
    value: '${counters.sets} open source'
functions:
  getIconsCSS: '/docs/libraries/utils/get-icons-css.md'

SVG for icons without coding

You can get SVG for icons without writing any code.

There are 2 options:

If you would rather generate SVG programmatically, consider using Iconify Utils.

Websites

You can browse all available icons and copy code or SVG on the following websites:

include usage/options/websites

Find icon you want, select it, copy SVG to clipboard, paste it in your HTML.

API

If you know the name of the icon you want to use, you can download SVG from Iconify API.

Iconify API is an open source hosted (or self-hosted) service for developers. Public Iconify API servers host over 60,000 icons from more than 70 open source icon sets.

You can get icons from public API by visiting URLs like this: [url]https://api.iconify.design/mdi-light/home.svg.

Replace [icon]mdi-light with icon set prefix, [icon]home with icon name.

Optional parameters:

Example: [url]https://api.iconify.design/ri/account-box-line.svg?height=none&color=%23000&box=1

Process:

See Iconify API documentation for details and more parameters.

Usage

index

title: Unplugin Icons
replacements:
  - code: '60,000'
    value: '${counters.icons}'
  - code: '60k'
    value: '${counters.icons-short}'

Unplugin Icons

Unplugin Icons is a plug-in that dynamically generates icon components.

You can use it to render icons if you are building an app using one of the following UI frameworks:

With Unplugin Icons, you can easily use over 60,000 open source icons and custom icons with minimal code.

How does it work? {#process}

It is a plug-in that works with practically all modern build tools, generating components dynamically as needed.

React example {#react}

import HomeIcon from '~icons/mdi/home';

function Demo() {
	return (
		<p>
			Home icon: <HomeIcon />
		</p>
	);
}

Vue example {#vue}

Example of Vue template:

<script setup lang="ts">
import MdiHome from 'virtual:icons/mdi/home';
</script>

<template>
	<p>Home icon: <MdiHome /></p>
</template>

Installation and usage

Installation and usage instructions depend on what build tools and UI framework you are using.

See Unplugin Icons readme for instructions.

Examples

If you want to see full examples, which include both configuration and templates, check out Unplugin Icons examples.

Custom icons

You can use Unplugin Icons with custom icons.

With Iconify Tools you can import, clean up and optimise icons and use them with Unplugin Icons.

You can find a working example in Iconify Tools repository, see [file]vite.config.ts for example of config that loads custom icons.

Functions are documented in Iconify Tools section of this documentation.

Usage

index

title: Generate SVG with Iconify Utils
functions:
  parseIconSetAsync: '/docs/libraries/utils/parse-icon-set.md'
  getIconData: '/docs/libraries/utils/get-icon-data.md'
  iconToSVG: '/docs/libraries/utils/icon-to-svg.md'
  iconToHTML: '/docs/libraries/utils/icon-to-html.md'

Generate SVG with Iconify Utils

This method requires a bit of coding, using Node.js.

If you are not using Node.js or not comfortable with the code below, consider other methods of generating CSS for icons.

Process

How it works:

In the end, you'll have thousands of SVG files, which you can embed in HTML.

How you embed SVG in HTML depends on your project. If you can't automate it, simply copy/paste code from [file].svg file to [file].html file where you want to use icon.

Node.js {#node}

If you do not have a Node.js app, you need to create one to generate CSS.

There are plenty of tutorials on how Node.js works, short version of steps:

Dependencies

You need to install 2 dependencies:

To install them, run

npm install --save-dev @iconify/utils @iconify/json

Scripts

There are two sample scripts, use whichever works better for your use case:

Export all icons

This script exports all icons from icon set as [file].svg files.

Process of generating SVG files is simple:

src: usage/svg-utils.js

Change options, run it to export SVG files.

Functions from Iconify Utils used in sample:

Get SVG for icon

This script generates SVG for selected icon.

You can use that function in your build process to generate SVG, which you can embed in HTML.

Process of generating SVG:

src: usage/svg-func-utils.js

Functions from Iconify Utils used in sample:

Usage

css

title: Customising icons with CSS variables

Customising icons with CSS variables

This applies to all SVG + CSS component packages:

You can customise icons using CSS variables, without editing icons.

This is done by setting custom CSS variables, which override default values used in icons. See examples below.

What is customisable?

The following properties can be customised:

Variable names

Variables are generated based on icon content (see examples below):

Variable names are generated from original value in lower case, replacing:

Examples:

Examples

Usage examples with usable CSS

Stroke width

Example customising stroke width in Tabler Icons:

svg {
  /* replace 2px stroke width with 1.5px */
  --svg-stroke-width--2px: 1.5px;
}

Opacity

Example customising opacity in two tone Google Material Icons:

svg {
  /* replace 0.3 with 0.5 */
  --svg-opacity--0-3: 0.5;
}

Example customising opacity in two tone IconaMoon:

svg {
  /* replace 0.15 with 0.4 */
  --svg-opacity--0-16: 0.4;
}

Colors

Example customising colors in Freehand color icons:

svg {
  /* replace blue color */
  --svg-color--0c6fff: red;
  /* replace black color */
  --svg-color--020202: currentColor;
}

This does not apply to [prop]currentColor used in monotone icons.

To change [prop]currentColor, simply change text color:

svg {
  color: red;
}

Icon specific variables

To customise icon, first you need to know what colors, opacity and stroke-width values are used in that specific icon.

Most icon sets are consistent, icons in one icon set usually use the same value, however, that is not always the case.

Inspect icon

Where to see actual variables used in a specific icon?

Currently the only way is to inspect icon in browser or editor.

Soon you will be able to do that on Iconify icon sets website.

Usage

index

title: Using icons as SVG + CSS
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "60k"
    value: "${counters.icons-short}"

Using icons as SVG + CSS

SVG + CSS method of rendering icons splits icon in two parts:

See rendering icon as SVG + CSS article.

Example

This is an example of SVG + CSS icon code.

SVG contains only minimal amount of code, reducing HTML size:

<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
    <path class="mdi-account-box" />
</svg>

Each shape has a class name instead of a long shape. CSS has a selector with that class name and shape data:

.mdi-account-box {
  fill: currentColor;
  d: path(
    "M6 17c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1H6m9-9a3 3 0 0 1-3 3a3 3 0 0 1-3-3a3 3 0 0 1 3-3a3 3 0 0 1 3 3M3 5v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2"
  );
}

Advantages

The biggest advantages of SVG+CSS is compactness and caching:

Additionally, you can use the full power of CSS:

Size comparison

The biggest benefit is with animated icons.

Icon with CSS animations has much smaller file size, which is a huge advantage: 176 bytes vs 1.29 kb!

This comes at cost of increasing CSS file size (by 1.29 KB in this case), but CSS files are usually shared between pages and are cached in browser.

Disadvantages

There is only one disadvantage of using SVG + CSS: Safari browser support.

Safari browser

The biggest part of icons is always the path, defined in [prop]d property of [tag]path element.

As shown in example above, in CSS it can be used with [func]path() function.

However, currently the latest version of Safari (26.3) does not support it!

Solution: using components to render icon, detect incompatible browsers and use a different rendering method for those browsers.

Convert icons

You can convert icons using an online script for converting SVG to SVG+CSS.

This converter does not do optimisation and clean up, use it with cleaned up SVGs.

Icon components

Because currently rendering icon as SVG+CSS requires a fallback for Safari browser, rendering methods are very limited and require JavaScript.

Currently, Iconify provides SVG+CSS solutions for the following frameworks:

Additionally, Iconify Unplugin can render icons on demand for all frameworks listed above.

Customise icons

If you want to change icon color in a monotone icon, change text color.

If you want to change something else, like a specific color or opacity or stroke-width, you can customise icons using CSS variables.

See Customising icons with CSS variables article.

Usage

index

title: SVG + CSS for React
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "60k"
    value: "${counters.icons-short}"

Using icons as SVG + CSS in React

Iconify provides easy to use components for rendering icons as SVG + CSS.

These components render:

If you want to know more details, see article on how Safari fallback works.

Usage

  1. Install a package for an icon set:
npm install @iconify-react/material-symbols
  1. Import icon in your React component:
import DraftsIcon from "@iconify-react/material-symbols/drafts";
  1. Use icon in your code:
<DraftsIcon />

Replace:

Browse Iconify icon sets to see all available icons.

Color

Monotone icons use text color for icon, to change icon color, change text color via CSS (inline or in stylesheet):

<DraftsIcon style={{ color: "red" }} />

Size

Unlike other components, SVG + CSS components do not set icon size. This has advantages and disadvantages.

Disadvantages:

Advantages:

You can change icon size by:

Properties

All icon components support [prop]width and [prop]height properties.

Value is a string.

You do not need to set both properties. If you set one property, other property will automatically be calculated from icon's width/height ratio.

Examples:

<DraftsIcon height="1em" />
<DraftsIcon width="1em" height="1em" />
<DraftsIcon height="24" />

CSS

You can control icon size in CSS, like for any other SVG.

.drafts-icon {
  width: 1em;
  height: 1em;
}
<DraftsIcon className="drafts-icon" />

Fallback component

For browsers that do not support SVG + CSS, these icon components use a fallback component.

Fallback component detects outdated browsers, loads full icon from Iconify API and renders it instead of small SVG.

Fallback icon is loaded on demand, only for visitors that use outdated browsers. Users with modern browsers will not be loading anything from API.

For React, fallback icon component is published in package [npm]@iconify/css-react.

In future, when Safari browser will support [func]path() function for [prop]d property, it will not be required, but for now it is bundled with icons.

Usage

index

title: SVG + CSS for SolidJS
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "60k"
    value: "${counters.icons-short}"

Using icons as SVG + CSS in SolidJS

Iconify provides easy to use components for rendering icons as SVG + CSS.

These components render:

If you want to know more details, see article on how Safari fallback works.

Usage

  1. Install a package for an icon set:
npm install @iconify-solid/material-symbols
  1. Import icon in your SolidJS component:
import DraftsIcon from "@iconify-solid/material-symbols/drafts";
  1. Use icon in your code:
<DraftsIcon />

Replace:

Browse Iconify icon sets to see all available icons.

Color

Monotone icons use text color for icon, to change icon color, change text color via CSS (inline or in stylesheet):

<DraftsIcon style="color: red;" />

Size

Unlike other components, SVG + CSS components do not set icon size. This has advantages and disadvantages.

Disadvantages:

Advantages:

You can change icon size by:

Properties

All icon components support [prop]width and [prop]height properties.

Value is a string.

You do not need to set both properties. If you set one property, other property will automatically be calculated from icon's width/height ratio.

Examples:

<DraftsIcon height="1em" />
<DraftsIcon width="1em" height="1em" />
<DraftsIcon height="24" />

CSS

You can control icon size in CSS, like for any other SVG.

.drafts-icon {
  width: 1em;
  height: 1em;
}
<DraftsIcon class="drafts-icon" />

Fallback component

For browsers that do not support SVG + CSS, these icon components use a fallback component.

Fallback component detects outdated browsers, loads full icon from Iconify API and renders it instead of small SVG.

Fallback icon is loaded on demand, only for visitors that use outdated browsers. Users with modern browsers will not be loading anything from API.

For SolidJS, fallback icon component is published in package [npm]@iconify/css-solid.

In future, when Safari browser will support [func]path() function for [prop]d property, it will not be required, but for now it is bundled with icons.

Usage

index

title: SVG + CSS for Svelte
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "60k"
    value: "${counters.icons-short}"

Using icons as SVG + CSS in Svelte

Iconify provides easy to use components for rendering icons as SVG + CSS.

These components render:

If you want to know more details, see article on how Safari fallback works.

Usage

  1. Install a package for an icon set:
npm install @iconify-svelte/material-symbols
  1. Import icon in your Svelte component:
import DraftsIcon from "@iconify-svelte/material-symbols/drafts";
  1. Use icon in your code:
<DraftsIcon />

Replace:

Browse Iconify icon sets to see all available icons.

Color

Monotone icons use text color for icon, to change icon color, change text color via CSS (inline or in stylesheet):

<DraftsIcon style="color: red;" />

Size

Unlike other components, SVG + CSS components do not set icon size. This has advantages and disadvantages.

Disadvantages:

Advantages:

You can change icon size by:

Properties

All icon components support [prop]width and [prop]height properties.

Value is a string.

You do not need to set both properties. If you set one property, other property will automatically be calculated from icon's width/height ratio.

Examples:

<DraftsIcon height="1em" />
<DraftsIcon width="1em" height="1em" />
<DraftsIcon height="24" />

CSS

You can control icon size in CSS, like for any other SVG.

.drafts-icon {
  width: 1em;
  height: 1em;
}
<DraftsIcon class="drafts-icon" />

Fallback component

For browsers that do not support SVG + CSS, these icon components use a fallback component.

Fallback component detects outdated browsers, loads full icon from Iconify API and renders it instead of small SVG.

Fallback icon is loaded on demand, only for visitors that use outdated browsers. Users with modern browsers will not be loading anything from API.

For Svelte, fallback icon component is published in package [npm]@iconify/css-svelte.

In future, when Safari browser will support [func]path() function for [prop]d property, it will not be required, but for now it is bundled with icons.

Usage

index

title: SVG + CSS for Vue
replacements:
  - code: "60,000"
    value: "${counters.icons}"
  - code: "60k"
    value: "${counters.icons-short}"

Using icons as SVG + CSS in Vue

Iconify provides easy to use components for rendering icons as SVG + CSS.

These components render:

If you want to know more details, see article on how Safari fallback works.

Usage

  1. Install a package for an icon set:
npm install @iconify-vue/material-symbols
  1. Import icon in your Vue component:
import DraftsIcon from "@iconify-vue/material-symbols/drafts";
  1. Use icon in your code:
<DraftsIcon />

Replace:

Browse Iconify icon sets to see all available icons.

Color

Monotone icons use text color for icon, to change icon color, change text color via CSS (inline or in stylesheet):

<DraftsIcon style="color: red;" />

Size

Unlike other components, SVG + CSS components do not set icon size. This has advantages and disadvantages.

Disadvantages:

Advantages:

You can change icon size by:

Properties

All icon components support [prop]width and [prop]height properties.

Value is a string.

You do not need to set both properties. If you set one property, other property will automatically be calculated from icon's width/height ratio.

Examples:

<DraftsIcon height="1em" />
<DraftsIcon width="1em" height="1em" />
<DraftsIcon height="24" />

CSS

You can control icon size in CSS, like for any other SVG.

.drafts-icon {
  width: 1em;
  height: 1em;
}
<DraftsIcon class="drafts-icon" />

Fallback component

For browsers that do not support SVG + CSS, these icon components use a fallback component.

Fallback component detects outdated browsers, loads full icon from Iconify API and renders it instead of small SVG.

Fallback icon is loaded on demand, only for visitors that use outdated browsers. Users with modern browsers will not be loading anything from API.

For Vue, fallback icon component is published in package [npm]@iconify/css-vue.

In future, when Safari browser will support [func]path() function for [prop]d property, it will not be required, but for now it is bundled with icons.