abachrome
How do I parse a CSS color string in Ruby?
Abachrome.parse accepts the full range of CSS color syntaxes — hex, rgb(), rgba(), hsl(), hsla(), oklab(), oklch(), and named colors — returning a unified Color object regardless of input format.
require 'abachrome'
colors = [
Abachrome.parse('#ff6b6b'),
Abachrome.parse('rgb(255, 107, 107)'),
Abachrome.parse('rgba(255, 107, 107, 0.8)'),
Abachrome.parse('hsl(0, 100%, 71%)'),
Abachrome.parse('oklch(0.7 0.18 22)'),
Abachrome.parse('coral'),
]
Converting Back to CSS
After parsing, convert to any output format:
color = Abachrome.parse('hsl(200, 80%, 50%)')
Abachrome::Outputs::CSS.format(color) # => "#19a3d4" (hex)
Abachrome::Outputs::CSS.format_rgb(color) # => "rgb(25, 163, 212)"
Working with Named Colors
All 140+ CSS/X11 named colors are supported:
colors = %w[tomato steelblue goldenrod mediumpurple].map do |name|
Abachrome.parse(name)
end
colors.each { |c| puts Abachrome::Outputs::CSS.format(c) }
# => "#ff6347"
# => "#4682b4"
# => "#daa520"
# => "#9370db"
Notes
- Parsing preserves the original values; no silent clamping occurs at parse time.
- Out-of-gamut values (common in
oklchwide-gamut inputs) can be mapped back withAbachrome::Gamut::SRGB.new.map(coordinates).