HTML Formatter & Minifier

Format unindented markup into structured HTML5 and SVG documents, or minify production templates to cut uncompressed byte volume without breaking CSS layouts or embedded scripts.

Options
Indent:
Input
Lines16
Size501 B
Beautified
<div class="card" id="main-card">
  <h2>Hello world</h2>
  <p>This is a <strong>sample</strong> paragraph with a
    <a href="https://example.com">link</a>.
  </p>


  <ul>
    <li>First</li>
    <li>Second</li>
    <li>Third</li>
  </ul>

  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <circle cx="12" cy="12" r="10"></circle>
    <path d="m9 12 2 2 4-4"></path>
  </svg>
</div>
Beautified in 1ms
Output19 lines · 439 B

Removed 2 HTML comments before formatting.

All formatting runs 100% locally in your browser — your HTML never leaves your device. Supports HTML5 and SVG.

Operation Guide

Step 1

Load or Paste Markup

Input raw markup directly into the editor or drop local .html, .svg, or .xml files.

Step 2

Select Processing Mode

Toggle Beautify (2-space, 4-space, or tab indents) or Minify (comment removal, inter-tag gap stripping, optional tag pruning).

Step 3

Review & Export Output

Inspect line counts, byte savings, and highlighted code, then copy to clipboard or download the sanitized file.

Transformation Examples

1. Unformatted Fragment → Structured HTML5 Tree

Input · Raw Single Line

<article class="card"><header><h3>Product Overview</h3><span class="badge">v2.4</span></header><p>High-performance rendering pipeline with <strong>zero layout shifts</strong>.</p><ul><li>Brotli compatible</li><li>Pre-parsed AST</li></ul></article>

Output · Beautify (2 Spaces)

<article class="card">
  <header>
    <h3>Product Overview</h3>
    <span class="badge">v2.4</span>
  </header>
  <p>High-performance rendering pipeline with <strong>zero layout shifts</strong>.</p>
  <ul>
    <li>Brotli compatible</li>
    <li>Pre-parsed AST</li>
  </ul>
</article>

2. Redundant Comments & Whitespace → Production Minification

Input · Development Template

<!-- Core Feature Card -->
<div class="card"   data-role="module" >
  <h3>Real-time Compression</h3>
  <p>
    Reduces document overhead by removing   superfluous whitespace runs.
  </p>
</div>

Output · Compact Minified String

<div class="card" data-role="module"><h3>Real-time Compression</h3><p>Reduces document overhead by removing superfluous whitespace runs.</p></div>

3. Inline SVG · Preserving XML Namespaces and Vector Coordinates

Input · Formatted SVG with XML Comments

<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor">
  <!-- Status Checkmark Icon -->
  <circle cx="12" cy="12" r="10" stroke-width="2"></circle>
  <path d="m9 12 2 2 4-4" stroke-width="2" stroke-linecap="round"></path>
</svg>

Output · Minified Vector Block

<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor"><circle cx="12" cy="12" r="10" stroke-width="2"></circle><path d="m9 12 2 2 4-4" stroke-width="2" stroke-linecap="round"></path></svg>

Processing Rules & Configuration Reference

SettingApplicable ModeMechanism & Safety Boundary
Indentation WidthBeautifyApplies 2 spaces, 4 spaces, or physical tabs per nesting level. Depth increments with open containers and decrements with closing tags.
Remove CommentsBeautify & MinifyStrips standard <!-- ... --> comment nodes across the document to reduce uncompressed markup size.
Strip Gaps Between TagsMinifyEliminates whitespace sequences between closing and opening tag brackets (> < → ><). Safe for block elements; verify inline-block button groups.
Collapse Text WhitespaceMinifyNormalizes multiple spaces, tabs, and line breaks within text nodes to a single space character, matching standard CSS inline rendering rules.
Remove Optional TagsMinify (Advanced)Prunes closing tags (</li>, </p>, </td>, </tr>, </option>) inferred by HTML5 parsers. Requires visual verification before production use.

The HTML Lexical Parsing & Transformation Pipeline

HTML is not a regular grammar and cannot be reliably parsed or transformed using simple global regular expressions. The WHATWG HTML Living Standard defines complex tokenization states, handling tag names, attributes, comments, doctypes, and character references. This tool executes a deterministic four-stage pipeline to format or compress documents without risking syntax corruption:

Stage 1

Protected Isolation

Extracts sensitive blocks (<pre>, <textarea>, <script>, <style>) and replaces them with collision-resistant sentinel tokens before whitespace processing.

Stage 2

Token Scanning

Scans tags, attributes, and text nodes. Identifies container elements versus void elements and normalizes superfluous spaces inside tag definitions (<div   class="...">).

Stage 3

Tree or Minify Pass

Beautify tracks container depth to calculate leading indentation. Minify strips non-essential inter-tag whitespace, collapses runs of spaces in text nodes, and drops comment tokens.

Stage 4

Block Reconstitution

Restores the isolated script, style, pre, and textarea payloads byte-for-byte into their placeholder slots, guaranteeing that code logic and preformatted text remain intact.

Whitespace Collapsing: HTML Parsing vs CSS Box Model

Under the CSS Text Module Level 3 and WHATWG specifications, web browsers apply strict rules when processing whitespace characters (ASCII space, tab, line feed, and carriage return). Understanding how whitespace behaves prevents unintended layout shifts when stripping HTML gaps:

Text Node Collapsing (white-space: normal)

In normal inline flow, any sequence of consecutive whitespace characters inside a text node collapses into a single space during browser layout calculation. Removing redundant spaces in source HTML reduces document size without changing the rendered visual output.

// Source: <p>High    performance   flow</p>
// Rendered: High performance flow

Inter-Tag Gaps in Inline Formatting Contexts

When elements have display: inline or inline-block, whitespace between their tags produces a visible gap (roughly 0.25em to 0.35em). Stripping > < into >< eliminates this spacing. Modern layouts should rely on CSS gap in Flexbox or Grid rather than markup whitespace.

// With whitespace: <a>One</a> <a>Two</a> → renders gap
// Minified: <a>One</a><a>Two</a> → elements touch

HTML5 Void Elements vs SVG / XML Namespaces

A common source of markup errors in formatters is treating all HTML tags as standard closing containers. HTML5 defines a specific list of void elements that never take end tags:

Element CategoryTag ListParser Closure RulesSelf-Closing Syntax (/>)
HTML5 Void Elementsarea, base, br, col, embed, hr, img, input, link, meta, source, track, wbrCannot have child nodes. End tags like </img> or </br> are invalid.The trailing slash (<br />) is completely ignored by HTML5 parsers; it is treated identically to <br>.
Inline SVG Elementscircle, ellipse, line, path, polygon, polyline, rect, stop, useParsed under the foreign XML namespace. Elements must be self-closing or closed explicitly.Self-closing syntax (<circle ... />) is mandatory if an end tag is omitted; otherwise subsequent elements nest inside.
Protected Raw Textscript, style, pre, textareaContent is treated as raw text or preformatted text. The closing tag is required.Cannot be self-closing. Internal whitespace and code syntax are preserved verbatim.

WHATWG Optional Closing Tag Omission & Structural Implications

According to section 8.1.2.4 of the WHATWG HTML standard, certain closing tags can be omitted because the browser parser determines their boundaries from contextual transitions:

Paragraphs (</p>)

A <p> tag’s end tag may be omitted if immediately followed by block elements: <address>, <article>, <div>, <ul>, or another <p>.

Lists (</li>, </dt>, </dd>)

An <li> tag’s end tag may be omitted if immediately followed by another <li> element, or if there is no more content in the parent container.

Tables (</td>, </tr>, </th>)

Table cells and rows close automatically when the parser encounters a subsequent cell or row tag, or when reaching the end of the enclosing <tbody> or table block.

Engineering Warning: While omitting optional closing tags shaves additional bytes from static markup, it can complicate JavaScript DOM traversal (e.g., node.parentElement expectations) and create unexpected matches with adjacent sibling CSS selectors (p + p). Test thoroughly before shipping omitted tags in complex web applications.

Network Compression vs HTML Minification (Minification vs Gzip/Brotli)

A common developer question is whether minifying HTML remains necessary when HTTP compression algorithms like Gzip or Brotli are active on the web server or CDN. In practice, minification and network compression operate at different layers and complement each other:

Uncompressed DOM Memory

The browser’s network layer decompresses the byte stream before passing text to the HTML parser. Smaller uncompressed HTML reduces memory allocation and string parsing load on low-power mobile CPU cores.

Speculative Preload Scanner

Modern browser engines run a lightweight background scanner on raw incoming HTML chunks to discover critical CSS, scripts, and font assets before DOM tree creation. Smaller files decrease scanner latency and advance asset discovery.

Dictionary Entropy Reduction

Gzip and Brotli use sliding-window dictionary matching (LZ77). Stripping non-repeating comments and random whitespace variations reduces the entropy pool, allowing the compression algorithm to allocate window capacity to recurring structural patterns.

Target Use Cases in Production Workflows

HTML Email Budgeting

Minify nested HTML table layouts to keep message size strictly under the 102 KB Gmail clipping threshold, preventing truncated email bodies.

Inline Critical Component HTML

Compress above-the-fold component markup embedded directly into server-side rendered (SSR) templates to minimize Time to First Byte (TTFB).

CMS & WYSIWYG Sanitization

Clean up bloated, inconsistently indented markup generated by rich-text editors and headless content management systems.

Debugging Minified Bundles

Reconstruct structured, indented markup from production single-line bundles for inspection, DOM auditing, and local debugging.

SVG Asset Optimization

Strip metadata comments and formatting whitespace from vector graphic files while preserving coordinate precision and XML namespaces.

CI/CD Pipeline Sanity Checks

Benchmark build tool output (such as HTMLMinifier or framework static site generators) against clean canonical formatting rules.

Frequently Asked Questions

What is the difference between formatting (beautifying) and minifying HTML?

Formatting (beautifying) expands compressed or unindented markup by adding hierarchical indentation (2 spaces, 4 spaces, or tabs) and line breaks, making the document readable and maintainable for developers during debugging. Minifying does the reverse: it strips comments, collapses redundant whitespace runs, and removes gaps between tags to produce the smallest valid markup for faster network delivery and browser parsing.

What exactly does an HTML minifier remove, and what is preserved?

Safe HTML minification strips standard HTML comments (<!-- ... -->), collapses consecutive whitespace characters inside text nodes into a single space, and removes whitespace between container tags. Sensitive raw blocks—specifically <pre>, <textarea>, <script>, and <style>—are isolated and preserved byte-for-byte so preformatted formatting, JavaScript logic, and CSS rules are never corrupted.

Will minifying HTML break inline JavaScript, CSS styles, or SVG graphics?

No. The parser extracts all <script> and <style> blocks prior to transformation, preventing single-line comments (//) from commenting out subsequent code or template literals from losing intentional spacing. Inline <svg> tags are treated under XML foreign namespace rules: viewBox coordinates, path data, and XML self-closing tags (<circle />, <path />) are strictly preserved.

Why should I minify HTML if my server or CDN already enables Gzip or Brotli?

Network compression (Gzip/Brotli) only reduces transfer size over the wire; the browser engine must decompress the stream back to raw markup before building the DOM. Minifying HTML reduces DOM tokenization overhead, speeds up the browser’s speculative preload scanner for critical assets, and lowers dictionary entropy so Brotli achieves higher compression ratios.

How does HTML minification resolve Gmail’s 102 KB email clipping limit?

Gmail automatically truncates HTML emails exceeding 102 KB (104,448 bytes) of uncompressed markup, hiding content behind a "View entire message" link that breaks conversion tracking and layout. Minifying table-heavy HTML email templates removes indentation, formatting comments, and inter-tag line breaks, typically shedding 20–40 KB and keeping emails safely below the threshold.

Why does removing whitespace between tags cause inline-block buttons or links to touch?

Elements rendered with display: inline or inline-block render whitespace characters between their tags as an approximate 4px gap. When a minifier strips inter-tag whitespace (> < into ><), that spacing vanishes. To prevent layout shifts, production layouts should rely on CSS gap in Flexbox or Grid, or explicit margin declarations rather than incidental markup whitespace.

How does HTML minification improve Google PageSpeed Insights and Core Web Vitals?

Minifying HTML directly improves Time to First Byte (TTFB) and reduces Document Request latency. Because the browser parser reaches critical <link rel="stylesheet"> and <script defer> tags in the <head> faster, the speculative preload scanner triggers critical asset discovery earlier, accelerating First Contentful Paint (FCP) and Largest Contentful Paint (LCP).

What does "Remove optional tags" do, and when is it safe to use?

Under WHATWG HTML5 section 8.1.2.4, browsers automatically infer closure for tags like </li>, </p>, </td>, and </tr> upon encountering subsequent block elements or parent boundaries. Stripping these tags yields extra byte savings, but can cause unintended side effects with CSS sibling combinators (p + p) or JavaScript DOM traversal (parentElement). It is best used for static, visually audited production builds.