CSS Minify & Beautify — JavaScript source
Minify CSS (strip comments and whitespace, shorten hexes and decimals) or beautify it back to readable one-declaration-per-line form. Strings stay intact. Runs locally with a shareable link.
This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
// css-minify — CSS minifier & beautifier. JavaScript port (canonical TS:
// src/lib/css-minify.ts; Go twin: cli/css-minify). One scanner masks string
// literals as \u0000n\u0000 sentinels and drops /* */ comments; every
// textual rule then runs on the masked text with RE2-compatible regexes (no
// lookaround) so the Go twin reproduces byte-identical output:
// minify — collapse whitespace, strip spaces around {} ; : , > (sibling
// + and ~ combinators keep theirs), drop the last semicolon before },
// lowercase hexes, shorten #aabbcc → #abc (never 8-digit alpha), strip
// leading zeros (0.5 → .5) and trailing fraction zeros (1.50 → 1.5,
// 1.00 → 1, .00 → 0).
// beautify — one selector per block, one declaration per line at 2-space
// depth, each declaration keeping its semicolon.
'use strict';
/** Scan CSS into a masked text where every string literal is replaced by a
* \u0000n\u0000 sentinel (n = index into `strings`). Comments are dropped. */
function mask(raw) {
let out = '';
const strings = [];
let i = 0;
while (i < raw.length) {
const ch = raw[i];
if (ch === '"' || ch === "'") {
const start = i;
i++;
while (i < raw.length && raw[i] !== ch) {
if (raw[i] === '\\' && i + 1 < raw.length) i++; // escaped char
i++;
}
if (i >= raw.length) return { error: 'Unterminated string' };
i++;
strings.push(raw.slice(start, i));
out += `\u0000${strings.length - 1}\u0000`;
} else if (ch === '/' && raw[i + 1] === '*') {
const end = raw.indexOf('*/', i + 2);
if (end === -1) return { error: 'Unterminated comment' };
i = end + 2;
} else {
out += ch;
i++;
}
}
return { masked: out, strings };
}
function unmask(text, strings) {
return text.replace(/\u0000(\d+)\u0000/g, (_, n) => strings[Number(n)]);
}
/** Conservative minification — see header for the exact rule list. */
function minifyCss(raw) {
const text = raw.trim();
if (!text) return { output: '', error: null };
const m = mask(text);
if (m.error) return { output: '', error: m.error };
let css = m.masked;
css = css
.replace(/\s+/g, ' ')
.replace(/\s*([{};:,>])\s*/g, '$1')
.replace(/;+}/g, '}')
.trim()
.replace(/#[0-9a-fA-F]{3,8}/g, (h) => h.toLowerCase())
.replace(/#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3([^0-9a-f]|$)/g, '#$1$2$3$4')
.replace(/(^|[^A-Za-z0-9_.#$%-])0+(\.[0-9]+)/g, '$1$2')
.replace(/(\.[0-9]*[1-9])0+([^0-9]|$)/g, '$1$2')
.replace(/(^|[^A-Za-z0-9_.#$%-])([0-9]+)\.0+([^0-9]|$)/g, '$1$2$3')
.replace(/(^|[^A-Za-z0-9_.#$%-])\.0+([^0-9]|$)/g, '$10$2');
return { output: unmask(css, m.strings), error: null };
}
/** Structural beautifier — 2-space indentation, declarations one per line. */
function beautifyCss(raw) {
const text = raw.trim();
if (!text) return { output: '', error: null };
const m = mask(text);
if (m.error) return { output: '', error: m.error };
const css = m.masked.replace(/\s+/g, ' ');
const strings = m.strings;
let out = '';
let buffer = '';
let depth = 0;
const pad = () => ' '.repeat(depth);
const flushDecl = (semi) => {
const decl = buffer.trim();
if (decl) out += `${pad()}${decl}${semi ? ';' : ''}\n`;
buffer = '';
};
for (let i = 0; i < css.length; i++) {
const ch = css[i];
if (ch === '{') {
const sel = buffer.trim();
buffer = '';
if (sel) out += `${pad()}${sel} {\n`;
else return { output: '', error: 'Block without a selector' };
depth++;
} else if (ch === '}') {
flushDecl(false);
depth--;
if (depth < 0) return { output: '', error: 'Unbalanced }' };
out += `${pad()}}\n`;
} else if (ch === ';') {
flushDecl(true);
} else {
buffer += ch;
}
}
if (depth !== 0) return { output: '', error: 'Unclosed block' };
flushDecl(false);
return { output: unmask(out, strings), error: null };
}
// Example:
// minifyCss('body { color : #AABBCC; margin : 0.50px; }').output
// → 'body{color:#abc;margin:.5px}'
// beautifyCss('a{b:c}').output → 'a {\n b: c;\n}\n'
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →