CSS Palette: Watch the Palette within a CSS

CSS Palette

I’ve written a quick toy to easily watch the colors used on a CSS. You pass the URL of an online CSS and it will parse the colors and build a palette for you. It’s useful if you want to reduce the amount of colors you’re using by spotting the almost duplicates that usually arise when writting code.

Color “sorting”

To display the colors in a nice order I wrote a “compare” color function to use with the sort method of the Array. It uses a basic color quantization by calculating the euclidean distance between the color and a origin at (0,0,0) black. Ruby code:

  #compares colors using the position 
def compare_colors(a,b)
color_position(rgb(b)) <=> color_position(rgb(a))
end

#returns the color "position" relative to (0,0,0) as euclidean distance
def color_position(rgb)
#Ruby 1.8.7 ya tiene reduce
#Math.sqrt(rgb.reduce{|dist,comp| dist+=comp*comp})
dist = 0
rgb.each{|comp| dist+=comp*comp}
Math.sqrt(dist)
end

One-line parse of the colors of the CSS

Once the CSS is downloaded with the standard net/http methods, it takes only one line to parse it and build an array of distinct colors (Ruby functional style is awesome):

   r.body.downcase.scan(/(#[0-9a-f]{3,6};)/mi).flatten.uniq

Generating the palette using DIVs

I wanted to show the colors as a single strip of squares that would resize with the browser window. This was a bit tricky because positioning DIV side by side had to be done by creating nested DIVs: the first one is displayed inline which makes possible to wrap the with the size of the window. The second div is displayed normaly as block and has a fixed size of 100x100px:

    

;background:<%="#{col[0]}"-%>;width:100px;height:100px;float:left"><%="#{col[0]}"-%>


The CSS Palette is permalinked on the rightbar.