webcolors
A pure-Python library for converting and normalizing HTML/CSS color names, hex codes, and RGB values
Repository Health
Technical Analysis
webcolors is a small, dependency-free Python library for working with the color formats defined by the HTML5 and CSS Color Module specifications. It converts between the named colors defined by those standards (e.g. “rebeccapurple”), hexadecimal notation, and integer RGB/RGB-percent tuples, applying the exact normalization and validation rules each spec requires.
Because it implements the specifications precisely rather than approximating common color libraries, webcolors is commonly used where strict conformance matters — HTML/CSS sanitizers, template engines, and design tools that need predictable, spec-correct color parsing.
What You Get
- Conversion functions between color names, hex strings, and integer/percent RGB tuples
- Separate HTML5 and CSS3 color-keyword tables, since the two specs define slightly different named-color sets
- Strict validation that rejects malformed hex or out-of-range RGB values instead of silently normalizing them
- A dependency-free, pure-Python implementation with full type hints
Common Use Cases
- Validating and normalizing user-supplied color values in HTML/CSS sanitizers or form inputs
- Converting color names to hex/RGB for design tools, template engines, or static-site generators
- Implementing spec-conformant color parsing in HTML5 parsers or CSS processors
- Round-tripping colors between human-readable names and machine-usable RGB tuples in data pipelines
Under The Hood
Architecture: The package is split into focused private modules — _definitions.py holds the HTML5 and CSS3 named-color tables, _conversion.py implements the hex/RGB/name conversion functions, _normalization.py applies each spec’s rounding and clamping rules, and _html5.py implements the HTML5-specific color-parsing algorithm — with __init__.py re-exporting the public API. Tech Stack: Pure Python with zero runtime dependencies, using modern typing (_types.py defines IntTuple/PercentTuple type aliases), packaged with a PDM-managed pyproject.toml and tested via nox. Code Quality: tests/ contains roughly 52 test functions across conversion, normalization, HTML5, and spec-conformance suites, including a dedicated test_conformance.py that checks behavior against the published specifications; the project has low recent commit velocity but is functionally stable and mature (10+ years old). API Design: The public API is a small, flat set of conversion functions (name_to_hex, hex_to_rgb, rgb_to_name, etc.) that are easy to memorize and require no setup, though users must pick the HTML5 vs CSS3 variant explicitly when the two specs diverge.