Minify HTML — Reduce Markup File Size

Learn how HTML minification works to reduce markup size by removing whitespace, comments, optional tags, and redundant attributes. Includes safe optimization techniques and common pitfalls.

HTML

Detailed Explanation

How HTML Minification Works

HTML minification reduces the size of HTML documents by removing characters that are not required by the browser's HTML parser. Unlike JavaScript and CSS, HTML minification must be more careful because whitespace can be visually significant.

What Gets Removed

<!-- Before minification -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <!-- Page title -->
  <title>My Page</title>
  <link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
  <div class="container">
    <h1>Hello World</h1>
    <p>Welcome to   my   website.</p>
  </div>
</body>
</html>

After minification:

<!doctype html><html lang=en><head><meta charset=UTF-8><title>My Page</title><link rel=stylesheet href=style.css></head><body><div class=container><h1>Hello World</h1><p>Welcome to my website.</div>

Key Optimizations

  1. Whitespace collapsing — Multiple spaces and newlines between tags are collapsed to a single space (or removed entirely between block elements).
  2. Comment removal — HTML comments (<!-- -->) are deleted. Conditional comments for IE can optionally be preserved.
  3. Attribute quote removal — Quotes around attribute values can be omitted when values contain no spaces or special characters (class="container" becomes class=container).
  4. Optional tag removal — HTML5 allows omitting some closing tags (</p>, </li>, </td>) and even some opening tags (<html>, <head>, <body>).
  5. Redundant attribute removaltype="text/css" on <link> and type="text/javascript" on <script> are defaults and can be removed.
  6. Boolean attribute shorteningchecked="checked" becomes just checked.

Tools for HTML Minification

  • html-minifier-terser — The most popular HTML minifier for Node.js.
  • HTMLMinifier — Original library, still widely used.
  • minify-html — Written in Rust, extremely fast.

Whitespace Sensitivity

Inside <pre>, <code>, <textarea>, and elements with white-space: pre, whitespace must be preserved. Good minifiers detect these contexts and skip whitespace collapsing within them.

Use Case

HTML minification is important for server-rendered pages and static sites where the HTML document itself is the critical resource. Reducing HTML size decreases Time to First Byte and speeds up initial DOM parsing, especially on document-heavy pages like landing pages and content sites.

Try It — Code Minifier

Open full tool