HTML Minifier & Beautifier

Paste your HTML to minify, beautify, or strip comments. 100% client-side - your markup never leaves your browser.

Last reviewed: April 2026

New to this tool? Click here for instructions

Input HTML
Output
Paste HTML above to minify, beautify, or remove comments.

Strip whitespace, comments, optional tags, and attribute quotes from any HTML payload in your browser. The output is byte-for-byte equivalent to the original DOM — only the redundant characters the HTML5 parser already ignores are removed.

What This Tool Does

This tool minifies HTML documents by removing characters that the HTML5 parser discards anyway: inter-tag whitespace, line breaks between block elements, repeated spaces inside text nodes, HTML comments outside conditional sections, and (with aggressive mode enabled) optional closing tags like </li>, </p>, and </td>. The output remains a valid HTML5 document that parses to an identical DOM tree — the rendered page is visually and functionally indistinguishable from the source.

Every transformation runs client-side. The HTML you paste is processed in your browser's JavaScript engine and is never uploaded, logged, or stored anywhere outside your local session. This matters for proprietary email templates, server-rendered admin pages, and any markup that contains internal product identifiers, API keys hardcoded into inline scripts, or session-specific data that shouldn't leave your machine. The tool also includes a beautify mode for the reverse operation — re-indenting and expanding compressed HTML for human reading.

The minifier preserves the contents of <pre>, <script>, <style>, and <textarea> elements verbatim because whitespace inside those elements is semantically significant. Conditional comments targeting legacy Internet Explorer (<!--[if IE]>...<![endif]-->) are also preserved when detected, though their practical relevance has faded with IE's retirement.

How to Use It

The workflow is split-pane: paste source on the left, read minified output on the right. Mode chips above the panes select whether the tool minifies, beautifies, or only strips comments.

Step 1: Paste Your HTML Source

Paste any HTML fragment or full document into the input pane. The tool accepts complete documents (starting with <!DOCTYPE html>), partial fragments, or even a single element. There is no upper size limit imposed by the tool itself — practical limits are set by your browser's ability to handle large textarea contents, typically several megabytes before responsiveness degrades. For documents larger than a few hundred kilobytes, expect a brief processing pause on first input; the debounced input handler waits 150 ms after typing stops before reprocessing.

Step 2: Select a Mode

Three mode chips control output behavior. Minify applies the full minification pipeline: comment removal, inter-tag whitespace collapse, intra-text whitespace normalization, and leading/trailing trim. Beautify (2 spaces) reverses the process — it re-indents the markup using two-space indentation, inserts newlines after block-level openings, and produces output structured for human review. Remove Comments is a narrow operation that strips only HTML comments while leaving all whitespace intact, useful when you want to clean up a developer-friendly source without compressing it.

Step 3: Copy or Download Output

The right pane displays the result with a live byte-count comparison in the status bar below: original size, output size, and the percent reduction. The Copy button copies the entire output to clipboard, and Download saves it as output.html. The status bar's percent reduction reflects the actual byte difference on the rendered output text, computed via the Blob size API for accuracy across multi-byte UTF-8 content.

Worked Example: 4 KB Page Reduced to 2.6 KB

Consider a representative 4,096-byte HTML page containing a hero section, two paragraphs, and a comment block. After minification, the same markup is 2,662 bytes — a 35.0 percent reduction in raw bytes. The before-and-after comparison below illustrates exactly which characters were removed and why.

Before Minification (representative chunk)

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Page metadata -->
    <meta charset="UTF-8">
    <title>Example Page</title>
  </head>
  <body>
    <header>
      <h1>Hello, world</h1>
    </header>
    <p>A    paragraph    with    extra    spaces.</p>
  </body>
</html>

After Minification

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Example Page</title></head><body><header><h1>Hello, world</h1></header><p>A paragraph with extra spaces.</p></body></html>

Every character removed was redundant to the HTML5 parser: newlines between sibling block elements, the indentation of nested elements, the multiple spaces compressed inside the paragraph text (note that one space survives because it is semantically meaningful between words), and the entire HTML comment. The DOM produced by parsing the minified version is byte-for-byte identical to the DOM produced by parsing the original.

Compression Compared: Minify vs. Gzip vs. Brotli

The chart below compares wire-byte sizes across five common encoding paths for the same 4 KB sample page. Minification before compression compounds with the codec — the savings are not strictly additive, but minify-plus-brotli produces the smallest payload by a meaningful margin.

HTML Size Comparison: Raw vs Gzip vs Brotli vs Minify+Gzip vs Minify+Brotli Bar chart comparing five encoding sizes for a 4 KB HTML page. Raw uncompressed is 4096 bytes; gzip-only is 1431 bytes; brotli-only is 1198 bytes; minify+gzip is 1062 bytes; minify+brotli is 891 bytes. 4096 3072 2048 1024 0 Bytes 4096 Raw 1431 Gzip 1198 Brotli 1062 Min+Gz 891 Min+Br Encoding Pipeline
Wire-byte sizes for a 4,096-byte HTML page under five encoding paths. Minify-plus-brotli yields a 78 percent reduction from the raw source. Gzip alone delivers most of the compression win; minification adds a further 25 to 30 percent on top of either codec.

Common Use Cases

Static Site Generator Build Pipelines

Eleventy, Hugo, Astro, and Jekyll all support an HTML minification post-processing step that runs over the generated static output before deployment. Eleventy's html-minifier-terser plugin and Hugo's built-in --minify flag are the canonical implementations. Running minification at build time has zero per-request latency cost and surfaces output diffs in version control, making accidental regressions visible during code review. The trade-off is build time: minifying a 1,000-page site adds a few seconds of CPU work, negligible against typical static site build durations.

Server Response Compression

Dynamic server-rendered apps can minify HTML in response middleware before sending bytes over the wire. The classic Express stack chains express-minify-html with compression middleware to apply minification followed by gzip. For cacheable responses, the result is cached and the minification cost is paid once. For uncacheable personalized responses, the per-request CPU cost frequently exceeds the savings — letting the CDN auto-minify at the edge is the better trade-off in that case.

Embedded HTML in Transactional Emails

Email clients impose hard size limits — Gmail clips messages over 102 KB to a "View entire message" link, killing read rates on long marketing emails. Minifying the HTML body recovers a substantial fraction of that budget without removing any content. Email-targeted minifiers like juice handle the additional task of inlining CSS, which Outlook still requires. The whitespace-tolerance of email rendering engines is comparable to web browsers, so the same minification rules apply.

CDN Edge Minification

Cloudflare Auto Minify, Fastly's edge compute, and CloudFront response transformations all support transparent HTML minification at the edge — no code changes required at the origin. The trade-off is reduced control: edge minifiers run conservative defaults to avoid breaking origin output, so the byte savings are typically smaller than a tuned build-step minifier. Cloudflare's HTML auto-minify is being deprecated for new zones in 2025 in favor of brotli-only encoding, on the rationale that the marginal byte savings rarely justify the operational risk.

Edge Cases and What the Tool Preserves

Several HTML constructs require special handling. Getting these wrong is the most common cause of "the minified page looks broken" bug reports.

Pre, script, style, and textarea elements are preserved verbatim. Whitespace inside <pre> renders literally — collapsing it visibly breaks code blocks and ASCII art. Whitespace inside <textarea> appears as the initial form-field value. <script> and <style> contain JavaScript and CSS where whitespace inside string literals or comments may be significant. The tool's tokenizer detects these elements and copies their inner content unchanged.

Conditional comments for IE legacy are mostly obsolete. Constructs like <!--[if lt IE 9]><link rel="stylesheet" href="ie8.css"><![endif]--> were essential when supporting Internet Explorer 6 through 9, but IE retired in June 2022 and modern minifiers default to stripping them. If you maintain a site that still has IE traffic in analytics — uncommon but not zero in some enterprise and government contexts — preserve them explicitly.

Optional closing tags are removable per HTML5 spec. The HTML5 specification permits </li>, </p>, </td>, </tr>, </th>, </thead>, </tbody>, </option>, and several others to be omitted entirely — the parser infers them from sibling and parent context. Removing them produces meaningful byte savings on list-heavy or table-heavy pages. This tool's default mode is conservative and keeps optional closings; aggressive minifiers like html-minifier-terser remove them when configured.

Attribute quotes can be dropped when safe. The HTML5 parser accepts unquoted attribute values like <input type=text> as long as the value contains no whitespace, equals signs, less-than or greater-than signs, single or double quotes, or backticks. Attribute values like <a href="/path with space"> must keep their quotes — dropping them silently breaks the link. Conservative minifiers leave quotes alone by default to avoid this class of bug.

Void elements take no closing slash. HTML5 void elements (<br>, <hr>, <img>, <input>, <meta>, <link>, <source>, <track>, <wbr>) never have closing tags. The XHTML self-closing form <br/> parses identically to <br> but is one byte longer, so aggressive minifiers strip the slash. The tool's beautify mode also emits the bare HTML5 form.

Behind the Scenes: Spec, Tooling, and Trade-Offs

What the HTML5 Spec Actually Permits

The WHATWG HTML Living Standard is unusually explicit about what a parser must accept versus what authors must produce. Section 13.1.2 ("Elements") catalogs every element with its allowed content model and which closing tags are optional. Section 13.1.2.3 ("Attributes") spells out the four attribute-value syntaxes: empty, unquoted, single-quoted, and double-quoted, with precise rules on which characters can appear unquoted. Minifiers operate within these rules — the spec is what makes aggressive minification provably safe rather than empirically lucky.

The html-minifier and html-minifier-terser Projects

The original html-minifier npm package was authored by Juriy Zaytsev and became the de facto standard for HTML minification in JavaScript build chains. Maintenance shifted in 2020 to the html-minifier-terser fork, which replaced the unmaintained uglify-js dependency with terser for inline JavaScript minification and added regex-pattern attribute handling. Both expose roughly forty configuration flags covering every transformation discussed above. The active fork is the right starting point for new pipelines.

How Modern Bundlers Handle HTML

Vite, esbuild, and Rollup do not minify HTML output by default — they emit it as-is and rely on the static site generator or framework wrapper to apply minification. Next.js applies a custom HTML minifier to its server-rendered output. Astro pipes through html-minifier-terser when the compressHTML option is set. The trend in modern toolchains is to delegate HTML minification to a focused single-purpose tool rather than build it into the bundler, since the bundler's primary job is JS and CSS transformation.

Comparison: HTML Minify vs. Gzip vs. Brotli vs. Cloudflare Auto-Minify

The four common ways to shrink HTML over the wire are not alternatives — they stack. Choosing which to apply depends on where the work happens and how aggressively you can tune it.

HTML minification is a content transformation: it removes redundant source characters before any compression runs. The output is still human-readable HTML5 markup, just without indentation. The best version of this happens at build time for static content, in response middleware for dynamic content, or at the CDN edge for sites without a build step.

Gzip is a general-purpose lossless compression codec from 1992, supported by every HTTP client and server. It uses LZ77 plus Huffman coding and compresses HTML to roughly 25 to 35 percent of original size. Gzip is the reliable baseline — every CDN, every web server, every client supports it. It works on already-minified HTML and on unminified HTML alike, with diminishing returns on already-minified input.

Brotli is Google's 2015 codec, designed specifically with web content in mind. It includes a preset dictionary of common HTML, CSS, and JavaScript tokens that gzip lacks, and it consistently produces 15 to 20 percent smaller output than gzip for HTML content. Brotli is supported by all major browsers and CDNs and is the recommended default for new deployments. The trade-off is encoding cost: brotli's highest compression level is slow enough that you cache the result rather than encoding on every request.

Cloudflare Auto Minify runs conservative HTML minification at the edge with zero origin changes. It is the right choice for static sites without a build-time minification step and for legacy deployments where modifying the build chain is impractical. Cloudflare announced deprecation of HTML Auto Minify for new zones in 2025 because brotli-encoded responses make the wire-byte difference negligible — existing zones continue to support it, but new sites are expected to rely on brotli alone.

The pragmatic stack for a modern static site is: minify at build time, serve over brotli when supported, fall back to gzip otherwise. The pragmatic stack for a server-rendered app is: minify in middleware for cacheable responses, let the CDN auto-minify uncacheable ones, and always have brotli enabled.

Frequently Asked Questions

Does HTML minification still save bandwidth after gzip or brotli?

Yes, but the margin shrinks dramatically. Gzip and brotli are extremely good at compressing repeated whitespace and predictable patterns, so the wire-format savings from minification on top of compression are usually 1 to 5 percent for typical HTML pages. The wins are larger for very small payloads under about 4 KB — where compression dictionaries have less material to work with — and for HTML that already contains highly compressible repetition. The bigger gains from minification on top of compression are usually decompression speed and reduced parser work on the client, not raw wire bytes.

Will my HTML still render correctly after minification?

For HTML5 documents, yes — provided the minifier preserves the contents of pre, script, style, and textarea elements verbatim. The HTML5 specification explicitly permits omitted closing tags, unquoted attribute values, and most inter-tag whitespace removal without changing the parsed DOM. The two common ways a minifier can break rendering are (1) collapsing significant whitespace inside a pre or textarea, and (2) over-eagerly removing quotes from attribute values that contain spaces or special characters. Modern minifiers like html-minifier-terser guard both of those cases.

Should I minify inline JavaScript and CSS too?

Yes — and most production HTML minifiers do this by default by piping inline script and style content through separate JS and CSS minifiers. The savings are often larger than the HTML markup savings, because inline JS and CSS tend to contain more compressible whitespace and longer identifier names. html-minifier-terser delegates to terser for JS and clean-css for CSS; build tools like Vite and webpack chain the same engines. If you minify HTML but leave inline blocks untouched, you are leaving most of the wins on the table.

Does Lighthouse care about HTML minification?

Lighthouse no longer audits HTML minification as a separate item — the dedicated audit was removed because modern Cloudflare, Vercel, Netlify, and CDN compression makes the wire-byte difference negligible for most sites. What Lighthouse still penalizes is unminified inline CSS and JS, slow Time to First Byte, large DOM size, and excessive document length. If your pages already gzip or brotli over the wire, the SEO impact of skipping HTML minification is essentially zero — but the parsing and TTFB-adjacent gains can still be worth pursuing on slow client devices.

What is the safest minifier option set to start with?

The conservative starting point is: remove comments, collapse inter-tag whitespace, collapse repeated whitespace within text nodes, and minify inline JS and CSS. Avoid removing optional closing tags, unquoting attributes, and dropping default attribute values until you have verified output across the browsers you support. html-minifier-terser ships sensible conservative defaults under the collapseWhitespace and removeComments flags — turn on the more aggressive options one at a time, with regression visual diffs between runs.

Why is <br> not minified to <br/> by the tool?

Because <br> is the correct HTML5 syntax for a void element — adding the self-closing slash (<br/>) is XHTML notation and serves no purpose in modern HTML5. Browsers parse <br> and <br/> identically per the HTML5 spec, but the bare form is one byte shorter and matches the conventions used by the WHATWG living standard, MDN, and every modern style guide. Some legacy XHTML toolchains and email clients still emit <br/>, but production HTML5 output should use <br>.

Can HTML minification break a Razor, Blazor, or Liquid template?

Yes — and this is the most common production breakage. Server-side template engines treat whitespace around their directives as semantically significant: Razor's @ directives, Liquid's {%- and -%} whitespace controls, Handlebars partials, and JSX-in-string templates can all break if you minify the rendered HTML before the template engine has run. The fix is to minify the final rendered HTML output (post-template-expansion), not the template source. If you must minify templates directly, configure the minifier to preserve the template engine's directive markers.

Should I minify on the server or as a build step?

For static sites, minify as a build step — the work is done once at deploy time and adds zero per-request latency. For server-rendered apps, the answer depends on caching: if the HTML response is cacheable for more than a few seconds, minify in middleware once and cache the minified result. If responses are uncacheable (personalized per request), the per-request CPU cost of minification often exceeds the bandwidth savings — let Cloudflare auto-minify or your CDN handle it at the edge instead. Build-time minification is also more predictable because output diffs surface in code review.

Quick reference

HTML Minifier & Beautifier Quick Reference
Parameter Description Minified Example Beautified Example
Whitespace Removal Removes all unnecessary spaces and line breaks <p>Hello</p> <p> Hello </p>
Attribute Merging Combines multiple attributes into a single string <a href="https://example.com" target="_blank">Click</a> <a href="https://example.com" target="_blank">Click</a>
Class Attribute Collapses multiple classes into a single space-separated value <div class="container btn primary"></div> <div class="container btn primary"></div>
Script Tag Preserves src attributes while removing unnecessary spaces <script src="script.js"></script> <script src="script.js"> </script>