Skip to content

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

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:

  • Install Node.js on your computer.
  • Create an empty directory, run npm init -y to create a basic project.

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:

  • getIconsCSS() generates CSS for selected icons from an icon set.
  • getIconCSS() generates CSS for one icon (uses icon as a source instead of an icon set).
  • getIconsContentCSS() renders selected icons from an icon set as content of pseudo-elements.
  • getIconContentCSS() renders one icon as content of pseudo-element (uses icon as source).

This tutorial shows how to use getIconsCSS(), which fits most use cases.

Build script

The process of building CSS is simple:

  • Load icon set.
  • Generate CSS for icons you need from that icon set.
  • Save it to .css file.
jsimport { readFile, writeFile } from 'node:fs/promises';
import { getIconsCSS } from '@iconify/utils';
import { locate } from '@iconify/json';

/**
* List of icons. Key is icon set prefix, value is array of icons
*
* @type {Record<string, string[]>}
*/

const icons = {
   'mdi': ['home', 'menu'],
   'mdi-light': ['alert-circle', 'circle', 'help-circle'],
};

// Parse each icon set
let code = '';
for (const prefix in icons) {
   // Find location of .json file
   const filename = locate(prefix);

   // Load file and parse it
   /** @type {import("@iconify/types").IconifyJSON} */
   const iconSet = JSON.parse(await readFile(filename, 'utf8'));

   // Get CSS
   const css = getIconsCSS(iconSet, icons[prefix]);

   // Add it to code
   code += css;
}

// Save CSS file
await writeFile('assets/style.css', code, 'utf8');
console.log(`Saved CSS (${code.length} bytes)`);

Change the list of icons, location of .css file, run it to build CSS.

Usage

To use those icons in HTML, use <span> elements with two class names: class name for the icon set, class name for the icon.

html<span class="icon--mdi-light icon--mdi-light--alert-circle"></span>

Options

There are options for getIconsCSS() that you can use to customise generated CSS.

See getIconsCSS() documentation.

Released under the Apache 2.0 License.