CSS Font Value Parser

2.0.1 · active · verified Sun Apr 19

css-font-parser is a lightweight JavaScript utility designed to accurately parse CSS `font` shorthand and `font-family` property values. It extracts structured data such as font size, line height, and a list of font families from a given CSS string. The package is currently at version 2.0.1, with its last publication approximately a year ago. Its release cadence is driven by necessary feature enhancements or bug fixes rather than strict timeframes, reflecting its focused scope. The library's primary differentiation lies in its simplicity and direct focus on parsing these specific CSS properties, providing a programmatic way to deconstruct complex font declarations without the overhead of a full CSS parser. It is particularly useful for tools that need to analyze or manipulate font styles based on their CSS declarations.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `parseFont` and `parseFontFamily` to extract structured data from CSS font strings, including handling complex font declarations and showing basic error handling for malformed input.

import { parseFont, parseFontFamily } from 'css-font-parser';

// Example 1: Parsing a basic font shorthand value
const parsedFont1 = parseFont('15px sans-serif');
console.log('Parsed Font 1:', parsedFont1);
/* Expected output:
{
  'font-family': ['sans-serif'],
  'font-size': '15px'
}
*/

// Example 2: Parsing a more complex font shorthand with line-height and multiple font families
const parsedFont2 = parseFont('15px/18px "Neue Helvetica", Helvetica, sans-serif');
console.log('Parsed Font 2:', parsedFont2);
/* Expected output:
{
  'font-family': ['Neue Helvetica', 'Helvetica', 'sans-serif'],
  'font-size': '15px',
  'line-height': '18px'
}
*/

// Example 3: Parsing only a font-family string
const parsedFontFamily = parseFontFamily('"Neue Helvetica", Helvetica, system-ui, sans-serif');
console.log('Parsed Font Family:', parsedFontFamily);
/* Expected output:
['Neue Helvetica', 'Helvetica', 'system-ui', 'sans-serif']
*/

// Example with potential error handling (library's error behavior not explicitly defined, so demonstrating usage)
try {
  const invalidFont = parseFont('invalid-font-value');
  console.log('Parsed Invalid Font (may be incomplete or throw):', invalidFont);
} catch (e) {
  console.error('Error parsing invalid font:', e.message);
}

view raw JSON →