Optimizing CSS can be achieved using CSSO.
Take a look at the sample input below:
input{margin:0}body{margin:0;background:white}
The CSSO output after optimization is:
input,body{margin:0}body{background:#fff}
(this is exactly what you are seeking)
Unfortunately, CSSO optimizes this as well:
.dont-care {
background-image: url("images/chart.png");
background-repeat: no-repeat;
}
Turning it into:
.dont-care{background-image:url("images/chart.png");background-repeat:no-repeat}
However, CSSTidy converts the above to shorthand property format:
.dont-care {
background:url("images/chart.png") no-repeat;
}
Four Seven steps for effective CSS optimization:
Here's my workflow:
- Combine CSS files into
all.css
.
- Input into CSSO.
- Click on Minimize
- Paste the optimized code in
all.min.css
So far, other than hiring @Grillz, I haven't found a better solution for CSS optimization.
Dealing with old IE hacks:
If you rely on CSS hacks for IE6 and 7, don't worry - CSSO will preserve them.
For instance:
.dont-care {
background-image: url("images/chart.png");
*background-image: url("images/chart.jpg");
background-repeat: no-repeat;
}
The resulting optimized code by CSSO is:
.dont-care{background-image:url("images/chart.png");*background-image:url("images/chart.jpg");background-repeat:no-repeat}
CSSTidy will ignore asterik(* hack used for IE6), and output:
.dont-care {
background:url("images/chart.jpg") no-repeat;
}
You may choose to avoid hacks altogether by creating a separate CSS file for older IE versions (e.g., all.oldIE.css). After optimizing both files separately (using the previous seven steps), include the following in your HTML/masterpage/template/layout file:
<!--[if lt IE 8]><link href="css/all.oldIE.min.css" rel="stylesheet" type="text/css"/><![endif]-->
<!--[if gt IE 7]><!--><link href="css/all.min.css" rel="stylesheet" type="text/css"/><!--<![endif]-->
where all.min.css
functions for all browsers except IE versions 7 or lower. However, solely relying on CSSO is a secure choice.
Update
It's advisable to skip the use of CSSTidy. CSSO provides safe optimizations. As stated by their developer in this post, shorthand optimization may not always be safe:
Consider this example:
.a{
background-attachment: fixed;
}
.b {
background-image: url("images/chart.png");
background-repeat: no-repeat;
}
If you have an element with both classes like this
<div class="a b"></div>
, optimizing .b could pose issues since it would conflict with the set properties in .a.
Therefore, this type of optimization may not be entirely safe.