abachrome

How do I parse a CSS color string in Ruby?

CSS colors arrive in many formats — hex, named colors, rgb(), hsl(), oklch(), and more. When your application needs to accept arbitrary CSS color input, a unified parser is valuable because it lets you work with all those formats through a single, consistent interface. Abachrome.parse handles the full range of CSS color syntaxes, 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'),
]

Each of these returns the same type of object. From that point on, you can convert, blend, or output the color in any format without caring which syntax it came from.

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)"

The original hsl() input is gone once you parse — Abachrome works with the underlying color value and re-emits in whatever format you request.

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"

Named colors are often useful when building tooling around design systems, where color names carry semantic meaning and need to be mapped back to their hex equivalents.

Notes

  • Parsing preserves the original values; no silent clamping occurs at parse time.
  • Out-of-gamut values (common in oklch wide-gamut inputs) can be mapped back with Abachrome::Gamut::SRGB.new.map(coordinates).