Hammerite Hammerite - 1 year ago 134
CSS Question

What exactly does ColorTranslator.FromHtml() support and why does it deviate from CSS color interpretation rules?

I want to add an option to an API for the user to specify the colour of something. I would like it to accept reasonable representations of colours, probably including hex representations and also the various CSS colours. At first glance

appeared to be what I needed, but after a little experimentation I'm not so sure.

The MSDN documentation, read incautiously, would seem to suggest that
should support CSS colour specifications. However, it doesn't appear to support every syntax provided by CSS. For example, this will throw an exception:

// "rgb(255 is not a valid value for Int32"
Color c = ColorTranslator.FromHtml("rgb(255,255,255)");

Other colours are parsed differently to the rules for CSS found here. An 8-digit hex code is interpreted as AARRGGBB instead of RRGGBBAA:

Color c = ColorTranslator.FromHtml("#aabbccdd");
// 187, 204, 221, 170
Console.WriteLine($"{c.R}, {c.G}, {c.B}, {c.A}");

A 4-digit hex code is interpreted as RRGG (with the blue part being zero) rather than RGBA:

Color c = ColorTranslator.FromHtml("#abcd");
// 0, 171, 205, 0
Console.WriteLine($"{c.R}, {c.G}, {c.B}, {c.A}");

Why do these deviations exist and what exactly does the method support? Is it just that the method is old and frozen at an older version of CSS, but with some extensions tacked on that clash with more recent CSS standards?

Answer Source

I can't tell you why but I can tell you what is supported.

If you read the Source you can see how the colours are handled, essentially:

  • #771122 handled as #RRGGBB
  • #712 handled as #RGB
  • LightGrey converted to LightGray
  • Any system colour names such as highlighttext are converted to specific colours.
  • Any other colour name will just be created using Color.FromName (I think)

This is from a time before most of the things you were referring to even existed in the spec I think.