Here is how to minify HTML: run your markup through an HTML minifier that collapses whitespace, strips comments, and removes redundant attributes and optional tags, then serve the result with gzip or Brotli compression. For a one-off file, paste it into an online HTML minifier; for a real site, add a minifier such as html-minifier, minify-html or @swc/html to your build so every deploy ships minified pages automatically.
That is the short answer. The longer one is that the safe settings matter more than the tool, and that compression does most of the byte-saving work. Below you will find what minification removes, which options can break a page, a size comparison I ran on three real pages with current tool versions, and copy-paste setups for the CLI, Vite, Astro and CI.
What HTML minification removes
An HTML minifier rewrites markup into a smaller document that a browser parses into the same DOM, or close enough that rendering does not change. Typical transformations, grouped by risk:
| Transformation | Example | Risk |
|---|---|---|
| Remove comments | <!-- build 42 --> dropped |
Safe, unless comments carry meaning (SSI, license notices, framework markers) |
| Collapse whitespace between block elements | Indentation between <li> items removed |
Safe |
| Collapse runs of whitespace in text | Hello, world becomes Hello, world |
Safe outside pre, textarea and CSS white-space: pre |
Remove default type attributes |
<script type="text/javascript"> becomes <script> |
Safe |
| Collapse boolean attributes | disabled="disabled" becomes disabled |
Safe |
| Remove redundant attributes | <input type="text"> becomes <input> |
Usually safe; breaks CSS like input[type="text"] if the stylesheet is external |
| Remove attribute quotes | class="nav" becomes class=nav |
Valid HTML, but trips naive regex-based tooling |
| Remove optional tags | </li>, </p>, <head>, </body> omitted |
Valid per the HTML spec, but harder to debug and risky with partial templates |
| Minify inline CSS, JS, JSON and SVG | <style> and <script> bodies minified |
Safe if the embedded minifier handles your syntax |
| Remove empty elements | <div class="spacer"></div> dropped |
Risky; JavaScript or CSS may target them |
The first five rows are what most people mean by "minify HTML", and they are almost always safe. The rest is where you trade a few extra percent for a chance of subtle breakage.
What is unsafe to minify
These are the failure modes I see most often in real projects.
Whitespace between inline elements
Whitespace between inline elements renders as a space. <strong>Price:</strong> <span>$10</span> shows "Price: $10"; delete that space and it becomes "Price:$10". Good minifiers know which elements are inline and keep one space, but they do not know about your CSS. If you style a span as display: block or you use custom elements (<my-badge>), the minifier's assumptions may be wrong. html-minifier has an inlineCustomElements option for exactly this, and conservativeCollapse always keeps one space instead of removing it entirely.
pre, textarea and white-space: pre
Whitespace inside <pre> and <textarea> is content. All the tools I tested leave the interior alone, but they do not all agree at the edges: in my test, html-minifier 5.4.1 trimmed the trailing newline and indentation before </pre>, while minify-html kept it exactly. That rarely matters visually, but if you compare rendered text in tests or use CSS white-space: pre-wrap on other elements, check those pages by hand.
Optional tags and unquoted attributes
The HTML standard really does allow omitting </li>, </p>, <html>, <head> and <body> in many contexts, and allows unquoted attribute values. Browsers parse the result correctly. The problems come from everything else that reads your HTML: regex-based scrapers, older template engines that inject fragments, and humans debugging production markup. minify-html removes optional tags by default (turn it off with keep_closing_tags and keep_html_and_head_opening_tags); html-minifier only does it when you enable removeOptionalTags or use the comprehensive preset.
Server-side templates
If you minify templates before rendering (PHP, Jinja, Handlebars, Liquid), the minifier has to skip template syntax. html-minifier ignores <?php ... ?> and <% ... %> by default and accepts more patterns through ignoreCustomFragments. The safer approach is usually to minify the rendered output, not the template source.
Invalid markup
Strict parsers refuse broken HTML. When I ran the MDN CORS guide through html-minifier and html-minifier-terser, both stopped with a parse error on a stray <?> in the page until I enabled continueOnParseError. minify-html and @swc/html processed it without complaint. If your CMS output is messy, either fix the markup or pick a tolerant tool, and never let a minifier failure silently ship an empty file.
How to minify HTML online
For a single page, an email template or a snippet you are about to paste into a CMS, an online tool is fastest. Paste the markup into the Butlermind Hub HTML Minifier, which removes whitespace, comments and redundant attributes, and copy the result. For the CSS and JavaScript you pull out of the page, the matching CSS and JS minifiers on the same developer-tools page do the equivalent job.
Online minification is fine for one-offs. For anything you deploy more than once, put it in the build so nobody has to remember the step.
How to minify HTML from the command line
html-minifier (Node.js)
The original html-minifier package by Juriy Zaytsev went years without a release, which is why forks such as html-minifier-terser became the default in many toolchains. That changed in late 2026: the html-minifier package is maintained again by Jens Oliver Meiert as version 5 (5.4.1 as of November 22, 2026), and the README offers a migration guide for users of his html-minifier-next fork. It is ESM-only and requires Node.js 22.13 or newer.
# One file, safe settings
npx html-minifier --preset conservative input.html -o output.html
# A whole build directory in place, aggressive settings
npx html-minifier --input-dir dist --output-dir dist --preset comprehensive
# Preview what would change without writing files
npx html-minifier --input-dir dist --dry --preset comprehensive
The two presets are a good starting point:
conservativeenablescollapseWhitespacewithconservativeCollapseandpreserveLineBreaks, plusremoveComments,collapseBooleanAttributesandremoveDefaultTypeAttributes.comprehensiveadds attribute-quote removal, optional-tag removal, redundant and empty attribute removal, entity decoding, and minification of inline CSS (via Lightning CSS), JavaScript, JSON and SVG.
Programmatic use is async:
import { minify } from 'html-minifier';
const html = await minify(source, {
preset: 'conservative',
minifyCSS: true,
minifyJS: true,
});
If you are on html-minifier-terser (last release 7.2.0 in April 2023), it still works and its options are largely the same, but it is no longer where development is happening.
minify-html (Rust, with Node and Python bindings)
minify-html is a Rust minifier with bindings for Node.js (@minify-html/node), Python (minify-html on PyPI), Deno, Ruby, Java and WASM, plus a minhtml CLI. It uses Lightning CSS and oxc for embedded CSS and JS. Version 0.18.1 is current.
pip install minify-html
import minify_html
with open("dist/index.html", encoding="utf-8") as f:
html = f.read()
minified = minify_html.minify(
html,
minify_css=True,
minify_js=True,
keep_closing_tags=True, # safer output
keep_html_and_head_opening_tags=True,
)
import minifyHtml from '@minify-html/node';
const out = minifyHtml.minify(Buffer.from(html), {
minify_css: true,
minify_js: true,
keep_closing_tags: true,
});
Every option defaults to false, and the defaults are already aggressive: optional tags are removed and attribute quotes dropped. The README lists four extra options (allow_noncompliant_unquoted_attribute_values, allow_optimal_entities, allow_removing_spaces_between_attributes, minify_doctype) that may produce markup that fails validation even though browsers parse it.
@swc/html
SWC ships an HTML minifier as @swc/html (1.16.22 at the time of writing). It is a good fit if SWC is already in your toolchain:
import { minify } from '@swc/html';
const { code } = await minify(Buffer.from(html), {
collapseWhitespaces: 'smart',
removeComments: true,
minifyCss: true,
minifyJs: true,
});
HTML minifier tools compared
| Tool | Version (Nov 2026) | Language | Interfaces | Notes |
|---|---|---|---|---|
html-minifier |
5.4.1 | JavaScript | CLI, Node API, config file | Most configurable; presets; strict parser by default |
html-minifier-terser |
7.2.0 (2023) | JavaScript | CLI, Node API | Widely embedded in older toolchains; no recent releases |
minify-html |
0.18.1 | Rust | CLI, Node, Python, Deno, Ruby, Java, WASM | Fast, tolerant of invalid HTML, aggressive defaults |
@swc/html |
1.16.22 | Rust | Node API | Good if you already use SWC |
| Online tool | n/a | n/a | Browser | Best for one-off snippets |
Real numbers: minified, gzip and Brotli sizes
I downloaded three public pages on November 26, 2026 and ran each through the tools above with Node.js 24. Gzip is level 6 and Brotli is quality 11, both via Node's zlib. Settings: html-minifier presets as named, with continueOnParseError on; html-minifier-terser with whitespace collapsing, comment removal, redundant and type-attribute removal and inline CSS/JS minification; minify-html with minify_css and minify_js; @swc/html with smart whitespace collapsing, comment removal and CSS/JS minification. Percentages are relative to the unminified page at the same compression level.
| Page | Original (raw / gzip / Brotli) | Best minifier, raw | Best minifier, gzip | Best minifier, Brotli |
|---|---|---|---|---|
| php.net PHP 8.6 release page | 113.9 / 22.0 / 17.2 KB | -23.4% | -18.8% | -17.1% |
| MDN CORS guide | 253.9 / 36.1 / 27.0 KB | -20.1% | -9.5% | -8.6% |
| Wikipedia "HTML" article | 787.0 / 122.6 / 87.9 KB | -6.4% | -2.8% | -1.5% |
After compression, the smallest file on every page came from html-minifier with the comprehensive preset, with @swc/html within about a tenth of a percentage point on the MDN and Wikipedia pages. On raw size, @swc/html (MDN) and minify-html (Wikipedia) matched it to within a few hundred bytes. On the php.net page, the conservative preset and the other three tools saved 5 to 7% after gzip.
Three conclusions from this small test:
- Hand-indented, server-rendered pages gain the most. The php.net page has deep indentation and inline code samples; Wikipedia's markup is already tight, so there is little to remove.
- Compression shrinks the gap. A 23% raw saving became about 17 to 19% after compression on the best page and under 3% on the worst. Minification still helps, but compression is doing most of the work.
- Aggressive settings matter more than tool choice. On the php.net page,
html-minifierwent from about -5% (conservative) to about -19% (comprehensive) after gzip. Differences between tools at similar settings were small.
These are three pages, not a benchmark suite. Run the same measurement on your own templates before you choose settings.
Minify vs gzip and Brotli compression
Minification and compression are complementary, not alternatives:
- Compression (gzip, Brotli, zstd) is lossless, reversible, and handled by your server or CDN. It removes repetition, and HTML is very repetitive. If you only do one thing, enable compression.
- Minification removes bytes the compressor would otherwise have to encode and shrinks the uncompressed document the browser must parse. The parsing benefit is small but real on large pages.
Check that compression is on:
curl -s -o /dev/null -w '%{size_download} bytes, encoding: ' \
-H 'Accept-Encoding: br, gzip' https://example.com/
curl -sI -H 'Accept-Encoding: br, gzip' https://example.com/ | grep -i content-encoding
If you precompress static files at build time with Brotli quality 11, the html-minifier README documents a tweak: add sortAttributes, keep attribute quotes, and force double quotes, because that makes the output more compressible even though the raw file grows slightly.
Smaller HTML helps the critical rendering path most on slow connections. It will not fix a slow server or heavy JavaScript; for interaction latency, see our guide to fixing INP (Interaction to Next Paint).
Framework defaults: does your build already minify HTML?
Vite
Vite 8 minifies JavaScript (Oxc by default) and CSS (Lightning CSS by default), but it does not minify index.html. I confirmed this with a Vite 8.3.8 build: comments, indentation and repeated spaces all survived. You can add a tiny plugin:
// vite.config.mjs (ESM: html-minifier v5 cannot be require()d)
import { defineConfig } from 'vite';
import { minify } from 'html-minifier';
export default defineConfig({
plugins: [
{
name: 'minify-html',
apply: 'build',
transformIndexHtml: {
order: 'post',
handler: (html) => minify(html, { preset: 'conservative' }),
},
},
],
});
Name the file vite.config.mjs or set "type": "module" in package.json; otherwise Vite bundles the config as CommonJS and fails to load the ESM-only package. More on the new toolchain in our Vite 8 migration guide.
Astro
Astro handles whitespace itself through the compressHTML option. Since Astro 7 the default is 'jsx', which applies React-style JSX whitespace rules; true removes whitespace losslessly from .astro components, and false keeps everything. Astro does not remove comments, optional tags or quotes, so a post-build pass with a minifier can still help on content-heavy sites. The trade-offs between Astro and Next.js output are covered in Astro vs Next.js.
Next.js and other React frameworks
JSX does not carry your source indentation into the rendered HTML, so server-rendered React output is already compact. Most of the remaining weight in a Next.js page is inline JSON payload and script tags, which an HTML minifier cannot shrink much. Measure before adding a step.
Static site generators
If your generator has no built-in minification, run the CLI on the output directory after the build, as shown next.
Add HTML minification to CI
The simplest reliable setup is a post-build step that fails loudly:
{
"scripts": {
"build": "vite build",
"postbuild": "html-minifier --input-dir dist --output-dir dist --preset conservative"
}
}
npm runs postbuild automatically after npm run build. In GitHub Actions:
- uses: actions/setup-node@v7
with:
node-version: 22
- run: npm ci
- run: npm run build # postbuild minifies dist/
- name: Guard against empty pages
run: |
find dist -name '*.html' -size -200c -print -exec false {} +
The last step fails the job if any HTML file is suspiciously small, which catches a minifier that errored and wrote nothing. Pair it with a visual or DOM snapshot test on two or three key templates when you first switch to aggressive settings, and track page weight over time with the rest of your technical SEO tooling.
Frequently Asked Questions
Does minifying HTML improve SEO?
Indirectly. Google does not rank pages higher because the HTML is minified, but smaller documents download and parse faster, which helps loading metrics on slow connections. The gain is usually modest compared with compression, caching and image optimization.
Is it safe to minify HTML?
The basic transformations (removing comments, collapsing whitespace between blocks, dropping default type attributes) are safe for almost every page. Removing optional tags, attribute quotes, redundant attributes and empty elements is valid HTML but can break CSS selectors, scripts or downstream tools, so test those settings first.
Should I minify HTML if I already use gzip or Brotli?
Yes, if it is cheap to add to your build. In my tests minification saved between about 1.5% and 19% on top of compression, depending on how much whitespace and inline code the page had. If you can only do one, enable compression first.
What is the best HTML minifier?
For configurability and the smallest output at aggressive settings, html-minifier v5 did best in my tests. For speed, tolerance of messy markup and Python or Rust projects, use minify-html. If SWC is already in your stack, @swc/html is a solid choice. For one-off snippets, use an online HTML minifier.
How do I minify HTML online for free?
Paste your markup into a free online HTML minifier, choose the options you want (comments, whitespace, attributes), and copy the output. Keep the original source, because minified HTML is hard to edit by hand.
Bottom Line
Minifying HTML is a cheap, low-risk optimization when you stick to whitespace and comment removal, and a modest extra win with aggressive settings that you have tested. Turn on gzip or Brotli first, then add html-minifier, minify-html or @swc/html as a post-build step with a guard in CI. Measure on your own pages: hand-indented server templates gain far more than already-compact framework output.