views:

256

answers:

3

How to convert all color code #XXYYZZ to shorter 3 character version #XYZ of whole css file?

+3  A: 

If you are just interested in minimizing the download size for your CSS file, you might use one of the many CSS compressors available (such as this one). And be sure to do the same with your javascript files while you are at it.

Adrian Grigore
+1 that's the only right way to do it. Everything else is just useless micro-optimization that makes the code harder to maintain (Search for #XYZ and #XXYYZZ .... )
Pekka
+1 for suggesting an existing CSS compressor
CrazyJugglerDrummer
+1  A: 

You can only shorten CSS colour codes to a 3 character version if they take the form

#XXYYZZ

Then they can be abbreviated

#XYZ

There are only 216 different codes which meet this requirement.

pavium
That's not an answer to the question.
stesch
I think it was. Earlier readers thought it was correct, too. Andrea Zilio's answer is much the same, although he expressed it in more words than I did.
pavium
Andrew updated his answer to give an actual method of accomplishing the problem.
CrazyJugglerDrummer
@CrazyJugglerDrummer: Look again. The edits are just a few characters.
stesch
I agree Andrea Zilio's answer is much more comprehensive and deserves to be approved, but it's also interesting that the question was edited to use my terminology. I can tell myself it's a *moral* victory, anyway.
pavium
+3  A: 

You can convert to the shorter 3-character version only colors expressed this way: #RRGGBB where the first and the second characters are the same, the third and fourth characters are the same and the fifth and sixth characters are the same.

So: #CC00DD can be shortened to #C0D while #CC01DD cannot.

A quick way to shorten all the possible colors in a CSS file is to open the file with an editor supporting regular expressions (for example kwrite or kate on linux) and replace (ignoring case) the following regular expression:

#([0-9A-F])\1([0-9A-F])\2([0-9A-F])\3

with this substitution text:

#\1\2\3

Tested with kate.

Otherwise you can use this tool where, if you only need to compress color codes, you can uncheck all the options except the "Compress color codes where possible".

Andrea Zilio