Every byte you send over the network costs time. Minification strips out everything a browser doesn't need — whitespace, comments, long variable names — and can cut file sizes by 30–80% without changing what the code does.
What is minification?
Minification is the process of removing unnecessary characters from source code without altering its functionality. The output is semantically identical to the input; it just looks unreadable to humans.
Characters that get removed or shortened:
- Whitespace — spaces, tabs, newlines used for indentation
- Comments —
/* block comments */,// line comments,<!-- HTML comments --> - Redundant syntax — trailing semicolons in some contexts, optional quotes
- Long names — variable/function names replaced with
a,b,c(JS only)
A 50 KB stylesheet can shrink to 35 KB. A 200 KB JavaScript bundle can drop to 80 KB. Over thousands of page views, the bandwidth savings are significant.
How CSS minification works
CSS minification is the safest form — it never renames anything, so the output is always correct.
Steps a CSS minifier takes:
- Remove comments (
/* ... */) - Collapse whitespace (newlines, indentation, multiple spaces → single space or nothing)
- Remove spaces around
{,},:,;,, - Remove the last semicolon before
} - Collapse shorthand values where safe (
0px→0,#ffffff→#fff) - Merge duplicate selectors (advanced minifiers only)
Before:
/* Card component */
.card {
background-color: #ffffff;
border-radius: 8px;
padding: 16px 16px 16px 16px;
margin: 0px;
}
.card:hover {
box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.15);
}
After:
.card{background-color:#fff;border-radius:8px;padding:16px;margin:0}.card:hover{box-shadow:0 4px 12px rgba(0,0,0,.15)}
Savings: 215 → 99 bytes (54% smaller).
How HTML minification works
HTML minification is slightly riskier than CSS because whitespace between inline elements can affect rendering. Safe HTML minifiers apply rules carefully:
- Remove HTML comments (
<!-- ... -->) except conditional comments (<!--[if IE]>) - Collapse whitespace in text nodes (multiple spaces → one space)
- Remove optional closing tags (
</li>,</td>,</p>in many contexts) - Remove optional attribute quotes where valid
- Remove default attribute values (
type="text/javascript",type="text/css") - Inline
<style>and<script>blocks are minified separately
Before:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Page title -->
<meta charset="UTF-8" />
<title>My Page</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<ul>
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
</ul>
</body>
</html>
After:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>My Page</title><link rel="stylesheet" href="styles.css"></head><body><ul><li>Item one<li>Item two<li>Item three</ul></body></html>
Savings: 302 → 192 bytes (36% smaller). For real pages with hundreds of elements, savings scale proportionally.
How JavaScript minification works
JS minification goes furthest because it can rename identifiers:
- Remove comments and whitespace (same as CSS/HTML)
- Mangle — rename local variables and function parameters to short names (
firstName→a) - Compress — fold constants, simplify boolean expressions, inline small functions
- Remove unreachable code (dead code elimination)
JS minification is done by tools like Terser, esbuild, or SWC — not typically done manually in code.
Quick reference: what each minifier removes
| What gets removed | CSS | HTML | JS |
|---|---|---|---|
| Whitespace / newlines | ✓ | ✓ (careful) | ✓ |
| Comments | ✓ | ✓ | ✓ |
| Optional quotes | — | ✓ | — |
| Optional closing tags | — | ✓ | — |
| Trailing semicolons | ✓ | — | ✓ |
0px → 0 |
✓ | — | — |
#ffffff → #fff |
✓ | — | — |
| Variable renaming | — | — | ✓ |
Code examples
CSS minifier (basic)
JavaScript:
function minifyCSS(css) {
return css
.replace(/\/\*[\s\S]*?\*\//g, '') // remove comments
.replace(/\s+/g, ' ') // collapse whitespace
.replace(/\s*([:{}|;,>~])\s*/g, '$1') // spaces around tokens
.replace(/;}/g, '}') // trailing semicolon before }
.trim();
}
Python:
import re
def minify_css(css: str) -> str:
css = re.sub(r'/\*[\s\S]*?\*/', '', css) # remove comments
css = re.sub(r'\s+', ' ', css) # collapse whitespace
css = re.sub(r'\s*([:{}|;,>~])\s*', r'\1', css) # spaces around tokens
css = css.replace(';}', '}') # trailing semicolon
return css.strip()
Go:
import "regexp"
func minifyCSS(css string) string {
comment := regexp.MustCompile(`/\*[\s\S]*?\*/`)
space := regexp.MustCompile(`\s+`)
tokens := regexp.MustCompile(`\s*([:{}|;,>~])\s*`)
css = comment.ReplaceAllString(css, "")
css = space.ReplaceAllString(css, " ")
css = tokens.ReplaceAllString(css, "$1")
css = strings.ReplaceAll(css, ";}", "}")
return strings.TrimSpace(css)
}
PHP:
function minify_css(string $css): string {
$css = preg_replace('/\/\*[\s\S]*?\*\//', '', $css);
$css = preg_replace('/\s+/', ' ', $css);
$css = preg_replace('/\s*([:{}|;,>~])\s*/', '$1', $css);
$css = str_replace(';}', '}', $css);
return trim($css);
}
HTML minifier (basic)
JavaScript:
function minifyHTML(html) {
return html
.replace(/<!--(?!\[if)[\s\S]*?-->/g, '') // remove comments (keep IE conditionals)
.replace(/\s+/g, ' ') // collapse whitespace
.replace(/>\s+</g, '><') // remove space between tags
.trim();
}
Python:
import re
def minify_html(html: str) -> str:
html = re.sub(r'<!--(?!\[if)[\s\S]*?-->', '', html) # remove comments
html = re.sub(r'\s+', ' ', html) # collapse whitespace
html = re.sub(r'>\s+<', '><', html) # space between tags
return html.strip()
Typical file size savings
| File type | Typical savings | Notes |
|---|---|---|
| CSS | 20–40% | More with colour shorthand and zero-value collapsing |
| HTML | 10–30% | Less if content-heavy pages |
| JS (whitespace only) | 20–35% | Comments + whitespace removed |
| JS (full mangle) | 40–70% | Variable renaming adds significant saving |
When to minify
Always minify for production. Minified files load faster for every visitor.
Never manually edit minified files. Keep the source files, minify as a build step (webpack, Vite, Parcel, or a CI pipeline command).
Use source maps in development. A source map file (.map) maps minified code back to the original, so DevTools shows readable code even when the served file is minified.
FAQ
Does minification break my code? Not if done correctly. Whitespace and comment removal is always safe. HTML tag omission follows the HTML specification. JS variable mangling only applies to local scope — global names and property names are left alone.
Is minification the same as compression (gzip)? No. They complement each other. Minification reduces the logical size (fewer characters). Compression (gzip, Brotli) reduces the transmitted size by encoding repeated byte patterns. Use both: minify first, then serve with gzip/Brotli enabled on your server.
Should I minify CSS and JS in WordPress? Yes, but use a plugin (WP Rocket, Autoptimize, LiteSpeed Cache) rather than doing it manually — they handle cache-busting and source maps automatically.
Can I reverse-engineer minified code? Comments and whitespace are gone permanently. Variable mangling is difficult to reverse (no perfect algorithm). Without a source map, minified code can be pretty-printed but not fully restored to its original variable names.
Does minifying HTML affect SEO? No. Search engine crawlers handle minified HTML identically to formatted HTML — the DOM is the same either way.
How much faster will my site be?
That depends on your current file sizes and the visitor's connection. A rule of thumb: every 100 KB saved from a critical render-blocking resource (CSS in <head>, render-blocking JS) can shave 50–200 ms off time-to-first-paint on mobile networks.