Key takeaways
- Minification removes comments and non-semantic whitespace. It is not the same as mangling identifiers, tree shaking or transpiling, and this site's minifiers do none of those.
- In HTML, whitespace is significant inside pre, textarea, script and style. Those four bodies must be preserved byte for byte, not collapsed.
- In JavaScript a newline can act as a semicolon. Joining a return statement to the expression on the next line changes what the function returns.
- In CSS, spaces inside calc() and between descendant selectors are operators. A licence comment marked with an exclamation mark is conventionally preserved.
- JSON is the safe case: whitespace is never semantic, so minifying it cannot change a value.
- Compression already removes repetitive whitespace almost for free. On a repetitive HTML payload gzip alone saved 98.2 percent and minifying first only improved that to 98.6 percent.
What Minification Is, and the Three Things It Is Not
Minification is a rewrite that produces a smaller document with identical behaviour. In practice that means removing comments, collapsing runs of whitespace, and dropping whitespace around punctuation where the language does not need it. The output is still the same program, the same stylesheet and the same page — just denser.
Three neighbouring operations are routinely conflated with it, and the distinction decides how much risk you are taking. Mangling renames local identifiers to short ones, which saves a great deal but requires real scope analysis; get it wrong and you break a closure or a property access. Tree shaking removes code that is never reached, which requires knowing the module graph and the side effects. Transpiling rewrites syntax for an older target, which can change semantics in either direction.
The minifiers here do none of those three. Verified on a 200-function payload: every identifier survives, so handler199 is still handler199 in the output, and every CSS selector survives, so .component-199 .child is still there. That is a deliberate trade. You get a smaller saving than a full optimising bundler would produce, and in exchange there is no scope analysis to get wrong and no possibility of a renamed variable colliding with a global.
For a one-off job — pasting a snippet into a chat, embedding a config in a URL, shrinking a single stylesheet before uploading it to a CMS that has no build step — that trade is the right one. For a production bundle you should use a real build pipeline, where minification is one stage among several and is tested as part of the build. The JavaScript minifier, HTML minifier and CSS minifier are for the first case, and they run entirely in your browser so the source never leaves your machine.
JSON Is the Easy Case, and It Sets the Baseline
Start with the language where nothing can go wrong, because it shows what minification looks like when the premise holds perfectly. In JSON, whitespace between tokens is never semantic. Newlines, indentation and the spaces after colons and commas exist only for human readers, and a parser discards them. So the JSON minifier can remove all of it with no risk whatsoever: every value, every key and every array element is bit-identical afterwards.
That is why JSON minification routinely saves 20 to 50 percent on a deeply indented document, and why the reverse operation — pretty-printing with the JSON formatter — is equally safe. They are opposite directions on the same lossless rewrite. The JSON formatter guide covers that pair in detail, including the five syntax mistakes that actually break JSON, which are a different problem from whitespace.
HTML, CSS and JavaScript do not share that property, and the rest of this guide is about where the premise fails. The useful mental model is that each language has a small set of contexts in which whitespace is data rather than decoration. A correct minifier identifies those contexts and shields them. An incorrect one applies a single global whitespace collapse and hopes.
HTML: Four Elements Where Whitespace Is the Content
Most HTML whitespace is decoration. The indentation between tags, the newlines inside a div, the spaces around an attribute list — a browser collapses all of it when rendering, so removing it changes nothing visible. Collapsing > whitespace < to >< and runs of spaces to a single space is safe in ordinary markup, and removing comments is safe too, with one exception noted below.
Four elements break that rule, and each for a different reason. pre renders its content verbatim, so collapsing spaces reflows the text and destroys the alignment that is the entire point of the element. textarea takes its content as the default value, so leading and trailing spaces and internal newlines are data the user will see and edit. script contains JavaScript, where a collapsed newline can change semantics through automatic semicolon insertion. style contains CSS, where a run of spaces inside a content: string is literal output text.
The correct implementation shields those four bodies before any collapsing happens and restores them byte for byte afterwards. That is what these tools do, and it was verified rather than assumed: a document containing a pre with deliberate double spaces and a newline, and a textarea with leading and trailing spaces, came out with both interiors exactly as they went in, while the surrounding markup still shrank. Measured on a small page, 226 bytes became 168, a 25.7 percent saving, with the protected regions intact.
The comment exception is conditional comments. <!--[if IE]> and its siblings were a real mechanism for targeting old Internet Explorer, and a minifier that strips them changes which markup those browsers see. The HTML minifier here preserves comments beginning with [if while removing ordinary ones. On a modern site that distinction is historical, but it is the difference between a lossless rewrite and a silent behaviour change.
One thing that is not a bug, because it is frequently reported as one: collapsing whitespace inside a code element. Inline code is not whitespace-preserving by default — it renders like ordinary inline text unless CSS says otherwise. So collapsing there is correct markup-level behaviour. The limitation is that no tool working on markup alone can know what your stylesheet does; see the CSS section below.
CSS: Spaces That Are Operators, and One Honest Limit
CSS has three places where a space is doing structural work. Inside calc(), the plus and minus operators must be surrounded by whitespace: calc(100% - 20px) is a subtraction, while calc(100% -20px) is parsed as a percentage followed by a negative length and is invalid. Between compound selectors, a space is the descendant combinator: .a .b means a .b inside an .a, while .a.b means one element carrying both classes. And in a content: string, spaces are literal output text.
The first two are preserved. Verified: calc(100% - 20px) survives intact, .a .b survives intact, and a licence comment written as /*! ... */ survives — the exclamation mark is the long-standing convention for "keep this through minification", used for copyright and licence headers that must not be stripped. Measured on a small stylesheet, 81 bytes became 69. Note that #ffffff was not shortened to #fff: colour shortening is an optimisation this minifier does not perform, which is consistent with the conservative scope described above.
The third is a real remaining limit, and it is better stated than hidden. A run of spaces inside a content: string is collapsed: .x::after { content: "hello world"; } comes out as content:"hello world". That changes the rendered text. If your stylesheet uses multi-space strings for alignment or visual spacing in generated content, check that output before shipping it, or replace the spaces with a non-breaking space entity or a padding rule, which is the more robust way to achieve the same layout anyway.
There is a second limitation that no markup-only tool can overcome, and any claim to the contrary is false. CSS can make an element whitespace-preserving with white-space: pre, pre-wrap or pre-line, and a div styled that way behaves like a pre even though its tag says nothing of the sort. Detecting that requires resolving the cascade against the actual document — computing which rules apply to which elements — which a text-only minifier does not do. The four shielded HTML elements are protected by tag name; elements made preformatted by a stylesheet are not, and cannot be.
JavaScript: A Newline Can Be a Semicolon
JavaScript has automatic semicolon insertion, and one of its rules is that a statement is terminated by a newline when the next token cannot continue it. The consequence for minification is that some newlines are load-bearing. Remove the wrong one and you do not get a smaller program, you get a different program or a syntax error.
The clearest case is return. Written as return on one line and 42; on the next, the function returns undefined, because ASI terminates the return statement at the newline. Join those two lines into return 42; and the function returns 42. That is a semantic change produced purely by deleting a newline. Verified: the minifier preserves that newline, and the minified function still returns undefined, exactly as the original did.
The subtler case is postfix ++ and --. These are only valid applied to a reference, so ASI separates them from a preceding expression that is not one. A string literal followed by a newline followed by ++y is two statements. Remove the newline and you get "x"++y, which is a SyntaxError: Invalid left-hand side expression in postfix operation. The same applies after a template literal, an object literal and a function expression. This was measured across fourteen adversarial cases: seven produced a syntax error before the fix and none do now.
The general rule the minifier follows is that a newline is kept whenever removing it would let two tokens merge into a different token or a different statement — between identifier characters, after a closing bracket or parenthesis, between digits and a following dot or digit, and before ++ or --. Everything else is collapsed. Measured on a small function, 97 bytes became 68, a 29.9 percent saving, with the ASI-critical newline preserved and every identifier unchanged.
A practical consequence worth internalising: you cannot verify a JavaScript minifier by looking at the output. You verify it by running both versions and comparing behaviour, including on inputs that almost parse. A minified file that is 30 percent smaller and throws on load is not an optimisation. If you are minifying anything you did not write, run it before you ship it.
Formatting Is the Same Problem in Reverse
Beautifying has exactly the same hazard as minifying, which is why it belongs in this guide rather than being treated as a separate concern. Adding indentation means inserting whitespace, and inserting it inside a pre, a textarea, a script or a style changes the content just as surely as removing it does.
The failure is easy to miss because the output looks better. A formatted textarea whose default value has gained two leading spaces still looks like tidy markup, but the user now sees an indented value in the field. A formatted pre block whose lines have been re-indented no longer shows the alignment the author intended. Verified: the HTML formatter shields the same four regions, so their interiors come out byte-identical while the surrounding markup is indented.
There is a cosmetic consequence of shielding that is worth knowing so you do not read it as a bug. A restored block is inserted verbatim, so only its first line carries the surrounding indentation; the rest of the block keeps its original internal layout, and the closing tag may end up on the same line as the following element. That is the correct trade: the content is preserved exactly, and the formatter does not pretend it can re-indent text whose whitespace is data.
The same principle applies to the CSS formatter and to JSON. Formatting JSON is unconditionally safe for the reason given above. Formatting CSS is safe because indentation between declarations is not semantic — with the same content: string caveat, since inserting a newline inside a quoted string would be a change too. When in doubt, format a copy and diff it against the original with the text diff tool; a diff that shows only whitespace outside quoted strings and protected elements is a diff you can accept.
The Numbers That Actually Matter: Minify Versus Compress
Here is the question most minification advice skips. Your server almost certainly already compresses responses with gzip or Brotli, and compression is extremely good at removing repetitive whitespace — which is most of what minification removes. So how much does minifying actually add? The answer was measured by running the minifiers and then compressing the exact output with gzip at level 9 and Brotli at quality 11.
On a 13,560-byte repetitive HTML payload: minifying alone saved 25.7 percent. Gzip alone saved 98.2 percent, taking it to 238 bytes. Minifying first and then gzipping gave 196 bytes — a total saving of 98.6 percent. So minification improved the compressed result by 17.6 percent of an already tiny number, and moved the overall saving by 0.4 percentage points. On content like this, compression is doing essentially all the work.
On a 16,690-byte CSS payload of 200 similar rules: gzip alone saved 96.0 percent, and minifying first improved the gzipped size by only 5.5 percent. But Brotli told a different story — 360 bytes became 291, a 19.2 percent improvement. Brotli's stronger modelling extracts more from the minified form than gzip does, so the value of minifying depends on which compressor you serve.
On a 28,780-byte JavaScript payload of 200 commented functions: minifying first cut the gzipped size from 1,232 bytes to 676 — a 45.1 percent improvement, and Brotli went from 599 to 369, a 38.4 percent improvement. The reason is that comments are *unique* text. Gzip can dedupe repeated indentation almost for free, but every // handler 42 is different, and removing them removes bytes compression could not have eliminated.
And the small-file case, which is genuinely counterintuitive: gzip can make a file bigger. An 81-byte stylesheet compressed to 96 bytes — 18.5 percent larger — because the gzip header and trailer cost around eighteen bytes before any compression happens. A 97-byte script compressed to 99 bytes. Below a few hundred bytes, compression is a net loss and minification is the only thing that helps.
- Repetitive HTML, 13,560 bytes: gzip alone 238 bytes; minify then gzip 196. Minification added 0.4 percentage points to the total saving.
- Repetitive CSS, 16,690 bytes: gzip 670 then 633 after minifying (5.5 percent better); Brotli 360 then 291 (19.2 percent better).
- Commented JavaScript, 28,780 bytes: gzip 1,232 then 676 after minifying (45.1 percent better); Brotli 599 then 369 (38.4 percent better).
- Tiny CSS, 81 bytes: gzip produced 96 bytes, which is larger than the input. Minification to 69 bytes was the only real saving.
- The pattern: compression removes repeated whitespace nearly for free, so minification pays off in proportion to how much unique text it removes — comments above all.
A Safe Routine Before You Ship Minified Output
The failures described above are all silent, so the routine has to be explicit rather than intuitive. One: know which language you are minifying and what its whitespace-sensitive contexts are. JSON has none. HTML has four elements. CSS has calc(), descendant combinators and quoted strings. JavaScript has ASI.
Two: check the protected regions survived. Search the output for a pre block, a textarea default value and a content: string with deliberate multiple spaces, and compare them against the input character by character. If any of them changed, the minifier is not safe for your document.
Three: for JavaScript, run both versions. Not just a syntax check — execute the code paths that matter, because the ASI failures produce a valid-looking file that returns the wrong value rather than one that fails to parse. A return that silently starts returning a number instead of undefined will pass every parse test you have.
Four: measure the compressed size, not the raw size, if the file will be served over HTTP with compression enabled. The raw saving is the number minifiers advertise and the compressed saving is the number your users experience, and as measured above they can differ by an order of magnitude in importance.
Five: keep the original. Minification is a build artefact, not a source of truth. If the only copy of your stylesheet is the minified one, you have lost the comments, the formatting and the ability to debug it — and no amount of byte saving is worth that. Format a copy when you need to read it, minify a copy when you need to ship it, and let the text diff tool confirm that the only differences are the ones you intended.
Frequently asked questions
The questions people ask most about minification: what is safe to strip, answered directly.