Saturday, December 16, 2006

CSS Shorthand Colors

I have seen plenty of articles on CSS shorthand (tips for conserving bytes in your CSS syntax), but I have never seen one that mentions when to use color names over their hexidecimal codes.

There are 16 colors names which are supported by all major browsers:
  1. white: #fff
  2. yellow: #ff0
  3. red: #ff0
  4. fuscia: #f0f
  5. silver: #c0c0c0
  6. gray: #808080
  7. olive: #808000
  8. purple: #800080
  9. maroon: #800000
  10. aqua: #f00
  11. lime: #0f0
  12. teal: #008080
  13. green: #008000
  14. blue: #00f
  15. navy: #000080
  16. black: #000

While there is a longer list of color names which are supported by some browsers, the 16 above are the only ones which can safely be assumed to be properly supported by all browsers. Its trivial to see that for 9 of the 16 colors it is shorter to use the color name, while in the other 7, its better to use the hex value.

Here are the color names you should remember and use over their hex values:
  1. red
  2. silver
  3. gray
  4. olive
  5. purple
  6. maroon
  7. teal
  8. green
  9. navy


Zach Leatherman said...

Have you recommended this tip to any of the CSS minifiers, like YUI compressor?

The Nerdbirder said...

@Zach Leatherman - Good question.

I was working on an ad hoc CSS minifier at the time. I can only assume that modern minifiers have discovered this (but I haven't verified).

I should clarify that I wouldn't recommend anyone attempt hand minification or worry about whether a color name or hex value is 1 byte shorter at this point.