Skip to content

Instantly share code, notes, and snippets.

@aufa
Last active January 10, 2016 15:17
Show Gist options
  • Save aufa/691b6d98a043f8b412b2 to your computer and use it in GitHub Desktop.
Save aufa/691b6d98a043f8b412b2 to your computer and use it in GitHub Desktop.
/**
* Minify CSS
* @param string css text
* @return sting minified css text
* @author awan <nawa@yahoo.com>
*/
function minifyCSS(text)
{
// check if css is string values
if (typeof text != 'string') {
return null;
}
return text
// repacle comment, tab and new line
.replace(/(\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+)/gm, '')
// replace multiple spaces with single spaces
.replace(/ {2,}/g, ' ')
// remove spaces after / brefore colon , semicolon and commas
.replace(/(?:(?: )?([{:}]|[;,]) )/g, '$1')
// remove semicolon if nearest of brackets
.replace(/\s*;\s*(})\s*/g, '$1')
// replace some spaces
.replace(/\s*([*$~^|]?=|[{};,>~+-]|\s+!important\b)\s*/gi, '$1')
// replaces some spaces inside brackets and colon
.replace(/([[(:])\s+|\s+([\]\)])|\s+(:)\s+/g, '$1$2$3')
// shorthand of hex color like #ffffff to #fff
.replace(/(\#((?:[a-f0-9]){3}))(\2)?\b/gi, '$1')
// shorthand replace muleiple twice hex color like #ddeeff to #def
.replace(/(#(?:([a-f0-9]){1}(?:\2)([a-f0-9]){1}(?:\3))([a-f0-9]){1}(?:\4))\b/gi, '#$2$3$4')
// trimming start or end css
.replace(/(^\s*)|(\s*$)/, '');
}
@aufa
Copy link
Author

aufa commented Jan 10, 2016

if you need PHP version that combine or minify css follow this link:

https://github.com/aufa/CssJsCombine

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment