merge selectors to optimize CSS

Dec 7, 2011 at 9:08 PM
Edited Dec 7, 2011 at 9:10 PM

CSS Selectors merging helps with crunching CSS but is it safe to merge selectors to further optimize CSS? Other css crunchers do this e.g. and CSSTidy. Are there any plans to add this feature to ajaxmin?

Dec 7, 2011 at 11:01 PM

Well, the answer is pretty much, "it depends." Sometimes there are some things that can be merged because no matter what the markup may look like underneath, one rule will override another and some rules and/or properties can be combined with others. Frequently, though, the structure of the markup (which we don't know at minification time) really can have a significant impact on the CSS as written, and assumptions can lead to different results. I'd love to add the combination-logic we can know to AjaxMin, but it would take a significant restructuring of the tool. Right now it outputs the CSS tokens as it parses them; to do a good combination process, it would have to parse it into an abstract syntax tree, work on the tree to modify and combine elements, and then output the results (the way it does with JavaScript). Unfortunately that might mean getting rid of support for comment-based CSS hacks, since it's greatly complicates things to have the comments in the syntax tree in a meaningful manner so that they get moved around with the code they are annotating. Most-likely I'd have to just throw out most comments, like we do on the JS side of the tool. Might be a good trade-off if we could get some significant savings through rule/property combination logic.

Dec 7, 2011 at 11:50 PM
Edited Dec 8, 2011 at 12:01 AM

Thanks for the input Ron! You're right about possible good trade-off. Just for experimental purpose I hacked ajaxminifer project to support merging common selectors. I added this functionality once everything is minified using CSS token approach. I took pretty naive approach and combined common selectors using regex. I'm getting expected output and reduction of almost 15% for the sample prod CSS I'm using from my project. I haven't done any more validation yet. 

I wanted to understand the challenges and issues that I could run into by merging selectors and also what approach I should take to validate this feature aside from small sample CSSs. 


For example