A comprehensive TypeScript library for parsing and serializing CSS property values with full MDN specification compliance
npm install @wix/css-property-parserA comprehensive TypeScript library for parsing and serializing CSS property values with full MDN specification compliance.
- 148 CSS Property Evaluators - Complete parsing support for layout, typography, colors, SVG, and more
- Dual Package Support - Works with both ESM (import) and CommonJS (require)
- MDN Compliant - Follows official CSS specifications exactly
- TypeScript First - Full type safety with comprehensive type definitions for all CSS values
- Round-Trip Stable - Parse โ serialize โ parse produces identical results
- CSS Functions - Supports calc(), min(), max(), clamp(), gradients, and more
- CSS Variables - Handles custom properties with fallback values
- SPX Units - Supports Wix's SPX (Scalable-Pixel) units alongside standard CSS units
- Performance Optimized - Fast parsing with minimal memory footprint
- 10,460+ Tests - Comprehensive test coverage across 168 test suites with 100% pass rate
- Shared Evaluator Pattern - 95% code reduction through intelligent code reuse
``bash`
npm install @wix/css-property-parser
typescript
import { Width, Height, Margin, Background, Font } from '@wix/css-property-parser';// Parse CSS values
const width = Width.parse('calc(100% - 20px)');
const background = Background.parse('linear-gradient(45deg, red, blue)');
// Serialize back to CSS
const widthCSS = Width.toCSSValue(width); // "calc(100% - 20px)"
const bgCSS = Background.toCSSValue(background); // "linear-gradient(45deg, red, blue)"
`$3
`javascript
const { Width, Height, Margin, Background, Font } = require('@wix/css-property-parser');// Parse CSS values
const width = Width.parse('calc(100% - 20px)');
const background = Background.parse('linear-gradient(45deg, red, blue)');
// Serialize back to CSS
const widthCSS = Width.toCSSValue(width); // "calc(100% - 20px)"
const bgCSS = Background.toCSSValue(background); // "linear-gradient(45deg, red, blue)"
`$3
`typescript
import {
Width, Height, Background, Font, Margin, Color, Position,
// Import types for parsed values
WidthValue, HeightValue, BackgroundValue, FontValue, MarginValue,
ColorValue, PositionValue, LengthPercentageValue,
// Import atomic types
CSSLengthValue, CSSPercentageValue, LengthValue, PercentageValue
} from '@wix/css-property-parser';// Use types for variables
const width: WidthValue | null = Width.parse('100px');
const background: BackgroundValue | null = Background.parse('red');
const margin: MarginValue | null = Margin.parse('10px 20px');
const color: ColorValue | null = Color.parse('#ff0000');
const position: PositionValue | null = Position.parse('absolute');
// Type-safe functions
function processWidth(value: string): WidthValue | null {
return Width.parse(value);
}
function serializeFont(font: FontValue): string {
return Font.toCSSValue(font) || '';
}
// All types are available from the main package for convenience
// This includes both property value types and atomic CSS types
`๐ฏ Advanced Examples
> Note: All examples work with both ESM (
import) and CommonJS (require). For TypeScript type imports, see Usage section above.`typescript
import { Width, Height, Margin, Background, Font } from '@wix/css-property-parser';// Parse CSS values with advanced features
const width = Width.parse('calc(100% - 20px)');
const height = Height.parse('50vh');
const margin = Margin.parse('10spx 20spx'); // SPX (Scalable-Pixel) support
const background = Background.parse('linear-gradient(45deg, red, blue)');
const font = Font.parse('bold 16px/1.5 "Helvetica Neue", Arial, sans-serif');
// Serialize back to CSS
const widthCSS = Width.toCSSValue(width); // "calc(100% - 20px)"
const heightCSS = Height.toCSSValue(height); // "50vh"
const marginCSS = Margin.toCSSValue(margin); // "10spx 20spx"
const bgCSS = Background.toCSSValue(background); // "linear-gradient(45deg, red, blue)"
const fontCSS = Font.toCSSValue(font); // "bold 16px/1.5 "Helvetica Neue", Arial, sans-serif"
`๐ API Reference
$3
Every property evaluator follows the same consistent API:
`typescript
interface PropertyEvaluator {
parse(value: string): T | null;
toCSSValue(parsed: T | null): string | null;
}
`$3
#### Layout Properties
`typescript
import { Width, Height, MinWidth, MaxWidth, MinHeight, MaxHeight } from '@wix/css-property-parser';// Sizing properties support lengths, percentages, and keywords
const width = Width.parse('50%'); // { value: 50, unit: '%' }
const height = Height.parse('auto'); // { keyword: 'auto' }
const minWidth = MinWidth.parse('0'); // { value: 0, unit: 'px' }
`#### Spacing Properties
`typescript
import { Margin, Padding, Gap, ColumnGap, RowGap } from '@wix/css-property-parser';// Shorthand properties expand to constituent parts
const margin = Margin.parse('10px 20px'); // Expands to top/right/bottom/left
const padding = Padding.parse('1em'); // Expands to all sides
const gap = Gap.parse('10px 20px'); // Row and column gaps
`#### Typography Properties
`typescript
import { FontSize, FontWeight, FontFamily, LineHeight, LetterSpacing } from '@wix/css-property-parser';// Font properties with comprehensive keyword support
const fontSize = FontSize.parse('1.2em'); // { type: 'length', value: 1.2, unit: 'em' }
const fontWeight = FontWeight.parse('bold'); // { type: 'keyword', keyword: 'bold' }
const fontFamily = FontFamily.parse('Arial, sans-serif'); // { type: 'font-list', families: ['Arial', 'sans-serif'] }
const lineHeight = LineHeight.parse('1.5'); // { type: 'number', value: 1.5 } (unitless)
`#### Complex Properties
`typescript
import { Background, Border, Font, TextShadow } from '@wix/css-property-parser';// Multi-value and shorthand properties
const background = Background.parse('url(bg.jpg) no-repeat center / cover');
const border = Border.parse('2px solid red');
const font = Font.parse('bold 16px/1.4 "Helvetica Neue", Arial, sans-serif');
const textShadow = TextShadow.parse('2px 2px 4px rgba(0,0,0,0.5)');
`$3
For parsing individual CSS data types:
`typescript
import {
LengthEvaluator,
PercentageEvaluator,
Color,
AngleEvaluator,
NumberEvaluator
} from '@wix/css-property-parser';// Parse individual CSS types
const length = LengthEvaluator.parse('10px'); // { value: 10, unit: 'px' }
const percentage = PercentageEvaluator.parse('50%'); // { value: 50, unit: '%' }
const color = Color.parse('#ff0000'); // { type: 'hex', value: 'ff0000' }
const angle = AngleEvaluator.parse('45deg'); // { value: 45, unit: 'deg' }
`๐ง Advanced Usage
$3
`typescript
import { Width, CssVariable } from '@wix/css-property-parser';// CSS variables are parsed but not resolved
const width = Width.parse('var(--main-width)');
// Returns: { CSSvariable: '--main-width' }
const widthWithFallback = Width.parse('var(--main-width, 100px)');
// Returns: { CSSvariable: '--main-width', defaultValue: '100px' }
`$3
`typescript
import { Width, FontSize } from '@wix/css-property-parser';// Calc expressions
const width = Width.parse('calc(100% - 20px)');
// Returns: { expression: '100% - 20px', function: 'calc' }
// Min/max/clamp functions
const fontSize = FontSize.parse('clamp(1rem, 2.5vw, 2rem)');
// Returns: { expression: '1rem, 2.5vw, 2rem', function: 'clamp' }
`$3
`typescript
import { Background } from '@wix/css-property-parser';const originalValue = 'linear-gradient(45deg, red 0%, blue 100%)';
const parsed = Background.parse(originalValue);
const serialized = Background.toCSSValue(parsed);
console.log(serialized === originalValue); // true
`๐จ Use Cases
$3
`typescript
import { FontSize, Color, Margin } from '@wix/css-property-parser';// Validate design tokens
function validateDesignToken(property: string, value: string): boolean {
switch (property) {
case 'font-size':
return FontSize.parse(value) !== null;
case 'color':
return Color.parse(value) !== null;
case 'margin':
return Margin.parse(value) !== null;
default:
return false;
}
}
`$3
`typescript
import { Width, Height, Background } from '@wix/css-property-parser';// Parse and transform CSS values
function processStyles(styles: Record) {
const processed: Record = {};
for (const [property, value] of Object.entries(styles)) {
switch (property) {
case 'width':
processed.width = Width.parse(value);
break;
case 'height':
processed.height = Height.parse(value);
break;
case 'background':
processed.background = Background.parse(value);
break;
}
}
return processed;
}
`$3
`typescript
import { Color, Background } from '@wix/css-property-parser';// Optimize CSS values
function optimizeColor(value: string): string {
const parsed = Color.parse(value);
if (parsed && parsed.type === 'hex') {
// Convert to shortest hex format
return Color.toCSSValue(parsed);
}
return value;
}
`๐ Documentation
- Evaluator Guide - Comprehensive guide for creating new property evaluators
- Pre-Commit Hook - Development workflow automation
๐งช Testing
`bash
Run all tests
npm testRun tests for specific property
npm test -- width.test.tsRun tests with coverage
npm test:coverageWatch mode for development
npm test:watch
`๐๏ธ Development
`bash
Install dependencies
npm installBuild TypeScript
npm run buildBuild with watch mode
npm run build:watchRun development server
npm run dev
`๐ Supported Properties
Total: 148 CSS Property Evaluators - All evaluators include full MDN compliance, comprehensive test coverage, and TypeScript type definitions.
> ๐ก Quick Reference: Use
{PropertyName}.parse(value) to parse and {PropertyName}.toCSSValue(parsed) to serialize any property below.$3
- Primitive Types: angle, color, length, number, percentage, string, time
- Composite Types: length-percentage, css-variable, blend-mode$3
- Standard Box Model: width, height, min-width, max-width, min-height, max-height
- CSS Logical Properties: block-size, inline-size, min-block-size, max-block-size, min-inline-size, max-inline-size$3
- Gap Properties (3): gap, column-gap, row-gap
- Margin Properties (7): margin (shorthand), margin-top, margin-right, margin-bottom, margin-left, margin-inline-start, margin-inline-end
- Padding Properties (7): padding (shorthand), padding-top, padding-right, padding-bottom, padding-left, padding-inline-start, padding-inline-end$3
- Border Shorthands (4): border, border-color, border-style, border-width
- Border Radius (5): border-radius, border-start-start-radius, border-start-end-radius, border-end-start-radius, border-end-end-radius
- Physical Borders (16):
- Shorthands: border-top, border-right, border-bottom, border-left
- Colors: border-top-color, border-right-color, border-bottom-color, border-left-color
- Styles: border-top-style, border-right-style, border-bottom-style, border-left-style
- Widths: border-top-width, border-right-width, border-bottom-width, border-left-width
- CSS Logical Block Borders (9):
- Shorthands: border-block, border-block-start, border-block-end
- Colors: border-block-start-color, border-block-end-color
- Styles: border-block-start-style, border-block-end-style
- Widths: border-block-start-width, border-block-end-width
- CSS Logical Inline Borders (9):
- Shorthands: border-inline, border-inline-start, border-inline-end
- Colors: border-inline-start-color, border-inline-end-color
- Styles: border-inline-start-style, border-inline-end-style
- Widths: border-inline-start-width, border-inline-end-width$3
- Font Properties (7): font (shorthand), font-family, font-size, font-weight, font-style, font-variant, font-stretch
- Text Properties (6): text-align, text-transform, text-decoration, text-shadow, text-overflow, text-indent
- Text Decoration Constituents (4): text-decoration-line, text-decoration-style, text-decoration-color, text-decoration-thickness
- Text Spacing (2): line-height, letter-spacing
- Text Flow (4): white-space, word-break, overflow-wrap, writing-mode$3
- CSS Grid Template (3): grid-template (shorthand), grid-template-columns, grid-template-rows
- CSS Grid Areas (3): grid-area, grid-column, grid-row
- CSS Grid Gaps (3): grid-gap (shorthand), grid-column-gap, grid-row-gap
- Layout Control (5): display, overflow, overflow-x, overflow-y, visibility$3
- Colors & Effects (4): background, color, opacity, box-shadow
- Blending & Compositing (2): mix-blend-mode, isolation
- Object Properties (2): object-fit, object-position
- Positioning (2): position, z-index
- Filters (2): filter, backdrop-filter$3
- Stroke Properties (3): stroke, stroke-width, stroke-opacity
- Fill Properties (2): fill, fill-opacity$3
- Flexbox & Grid Alignment (4): align-items, align-self, justify-content, flex-direction$3
- Shared Evaluator Pattern (8 shared): 95% code reduction through intelligent reuse
- Sizing properties: width/height variants
- Spacing properties: gap, margin, padding variants
- Border width properties: all border-width variants
- Border style properties: all border-style variants
- Border color properties: all border-color variants
- Border individual properties: border shorthand variants
- Logical border properties: block/inline border variants
- Logical border radius properties: corner radius variants- CSS Functions: Full support for
calc(), min(), max(), clamp(), var(), gradients
- SPX Units: Wix Scalable-Pixel units for responsive design
- Round-Trip Stability: Parse โ serialize โ parse produces identical results
- Performance: Optimized parsing with minimal memory footprint๐ค Contributing
1. Fork the repository
2. Create a feature branch
3. Add comprehensive tests (20+ tests minimum)
4. Ensure all tests pass
5. Follow the Evaluator Guide
6. Submit a pull request
๐ License
ISC License - see LICENSE file for details.
๐ Acknowledgments
- Built with MDN CSS specifications as the authoritative reference
- Inspired by the need for robust CSS parsing in modern web applications
- Comprehensive testing ensures production-ready reliability
- Enhanced and documented with assistance from Claude (Anthropic AI)
---
๐ Complete Evaluator Exports Reference
All evaluators are available as named exports from the main package. Use
import { EvaluatorName } from '@wix/css-property-parser' or const { EvaluatorName } = require('@wix/css-property-parser').$3
| Export Name | CSS Property/Type | Description |
|-------------|-------------------|-------------|
| AngleEvaluator | | CSS angle values (deg, rad, turn, grad) |
| BlendMode | mix-blend-mode, background-blend-mode | CSS blend mode keywords |
| Color | | CSS color values (hex, rgb, hsl, named, etc.) |
| CssVariable | var() | CSS custom properties and variables |
| LengthEvaluator | | CSS length values (px, em, rem, vh, etc.) |
| LengthPercentage | | Combined length and percentage values |
| NumberEvaluator | | CSS numeric values |
| PercentageEvaluator | | CSS percentage values |
| Position | position | CSS position keywords (static, relative, absolute, fixed, sticky) |
| StringEvaluator | | CSS string values |
| TimeEvaluator |