HTML Minifier & Code Compressor

Compress HTML markup code by stripping unnecessary whitespace, extra line breaks, and HTML comments to reduce payload size and boost web page load speeds.

How to Use the HTML Minifier

1

Input HTML Code

Paste any formatted or multi-line HTML code snippet into the input box.

2

Select Minification Options

Toggle options to remove HTML comments and collapse inter-tag whitespace.

3

Copy Minified Result

Click Minify HTML Code and copy optimized production-ready HTML for your site or template engine.

Tool Options

Boost Web Performance

Reduces document download payload size, improving Google PageSpeed scores and First Contentful Paint (FCP).

Comment Stripping

Removes development comments and whitespace to hide internal notes and reduce response size.

Deterministic REST API

Provides a free REST API endpoint (`POST /api/html/html-minifier`) for automated CI/CD build scripts.

Your Data Privacy

Web Tool
Privacy-First Architecture
Most of our web tools process your data entirely in-browser. Where server processing is technically required, payloads are evaluated statelessly in-memory and are never stored, saved, or logged.
REST API
Stateless In-Memory Processing
When you use our API endpoints, your requests are processed strictly in-memory without persistent database storage, disk logging, or data retention.
Want to learn more about how we safeguard your information and infrastructure?
Read our full Privacy Policy for detailed security standards, data retention principles, and compliance guarantees.

What does the HTML Minifier & Code Compressor do?

The HTML Minifier & Code Compressor strips redundant whitespace, line breaks, indentations, and HTML comments from raw HTML source code. It reduces document size and calculates compression metrics (original byte size, minified size, and percentage savings) to optimize web page load performance.

Core Concepts

Understanding HTML minification mechanics:

  • Comment Stripping: Removes standard HTML comments (<!-- ... -->) while preserving conditional comments where needed.
  • Inter-Tag Whitespace Collapsing: Removes whitespace between adjacent tags (e.g. > < becomes ><) and collapses consecutive spaces into single spaces.
  • Empty Attribute Stripping: Optionally removes empty attribute declarations (such as class="") to trim additional bytes.
  • Performance Metrics: Computes exact byte counts before and after compression to benchmark bandwidth savings.

How to use the tool?

  1. Paste HTML Markup: Paste your unminified HTML code or template into the input editor or click Load Sample.
  2. Configure Options: Toggle Remove HTML comments and Collapse inter-tag whitespace.
  3. Minify & Copy: Click Minify HTML Code, review the compression savings, and click Copy or Download to export the compressed markup.

Related Developer Utilities

If you work with HTML markup, code formatting, and web optimization, explore these complementary tools:

REST API Integration

Blueutils provides a free REST API endpoint (POST https://blueutils.com/api/html/html-minifier) to programmatically compress HTML markup code by stripping comments, inter-tag whitespace, and unnecessary line breaks.

API Request Parameters

Name Type Description Example
rawText String Raw HTML markup payload to minify. "<div>\n <h1>Title</h1>\n</div>"
options.removeComments Boolean Optional. Strip HTML comments. Default: true. true
options.collapseWhitespace Boolean Optional. Collapse inter-tag spaces. Default: true. true
options.removeEmptyAttributes Boolean Optional. Remove empty attributes like class="". Default: false. false

API Request Payload Examples

cURL

curl -X POST https://blueutils.com/api/html/html-minifier \
  -H "Content-Type: application/json" \
  -d '{
    "rawText": "<div>\n  <!-- Comment -->\n  <h1>Title</h1>\n</div>",
    "options": { "removeComments": true, "collapseWhitespace": true }
  }'

Python

import requests

url = "https://blueutils.com/api/html/html-minifier"
payload = {
    "rawText": "<div>\n  <!-- Comment -->\n  <h1>Title</h1>\n</div>",
    "options": { "removeComments": True, "collapseWhitespace": True }
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.json())

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String jsonPayload = """
            {
                "rawText": "<div>\\n  <!-- Comment -->\\n  <h1>Title</h1>\\n</div>",
                "options": { "removeComments": true, "collapseWhitespace": true }
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://blueutils.com/api/html/html-minifier"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

API Response Parameters

Name Type Description Example
isValid Boolean Indicates whether minification succeeded. true
originalSize Number Raw input byte size. 45
minifiedSize Number Minified output byte size. 24
bytesSaved Number Total bytes saved by minification. 21
compressionRatio String Percentage bandwidth savings. "46.67%"
minifiedText String Compressed HTML markup string. "<div><h1>Title</h1></div>"

API Response Payload Examples

Success Response (HTTP 200 OK)

{
  "isValid": true,
  "originalSize": 45,
  "minifiedSize": 24,
  "bytesSaved": 21,
  "compressionRatio": "46.67%",
  "removeComments": true,
  "collapseWhitespace": true,
  "minifiedText": "<div><h1>Title</h1></div>",
  "output": "<div><h1>Title</h1></div>"
}

Validation Failure Response (HTTP 400 Bad Request)

{
  "isValid": false,
  "error": "Invalid input: HTML payload to minify cannot be empty."
}

Rate Limit Exceeded Response (HTTP 429 Too Many Requests)

{
  "error": "API rate limit exceeded. Please wait or contact support@blueutils.com."
}

Why use an API to minify HTML?

Integrating the HTML Minifier API into static site generators, email template builders, or AI agent tool calling provides key benefits:

  • Rapid Script Validation: Compresses server-rendered templates, email payloads, and CMS pages before deployment to reduce cloud bandwidth costs.
  • Optimized Token Efficiency for AI Agents: LLMs frequently inject superfluous indentation into generated HTML. Calling the API compacts output code deterministically without consuming token budget.
  • Deterministic Accuracy Without Hallucinations: Ensures 100% regex-safe whitespace compression and accurate byte metric calculation.

Native Usage

How to minify HTML locally in terminal environments or scripts:

Windows (CMD / PowerShell)

# Minify HTML in PowerShell
(Get-Content -Path .\index.html -Raw) -replace '<!--[\s\S]*?-->', '' -replace '\s+', ' ' -replace '>\s+<', '><' | Set-Content min.html

Linux / Unix (Bash)

# Minify HTML using tr and sed in Linux
tr -d '\n\r' < index.html | sed -E 's/>[[:space:]]+</></g' > min.html

Python

Using Python re:

import re

html = "<div>\n  <!-- Comment -->\n  <h1>Title</h1>\n</div>"
minified = re.sub(r'<!--[\s\S]*?-->', '', html)
minified = re.sub(r'\s+', ' ', minified)
minified = re.sub(r'>\s+<', '><', minified).strip()
print(minified)

Java

Using Java String.replaceAll:

import java.nio.file.*;

public class HtmlMinifierExample {
    public static void main(String[] args) throws Exception {
        String html = Files.readString(Paths.get("index.html"));
        String minified = html
            .replaceAll("<!--[\\s\\S]*?-->", "")
            .replaceAll("\\s+", " ")
            .replaceAll(">\\s+<", "><")
            .trim();
        Files.writeString(Paths.get("min.html"), minified);
        System.out.println("Minified successfully.");
    }
}

Frequently Asked Questions (FAQ)

How do I minify HTML markup code online?

Paste your raw HTML document into the editor, configure compression options (remove comments, collapse inter-tag whitespace), and click Minify HTML Code.

How does HTML minification improve website performance?

Removing unnecessary spaces, line breaks, and HTML comments reduces byte size, speeding up HTTP document transfers and boosting Google Core Web Vitals scores.

Is my HTML code uploaded or stored on external servers?

No. All HTML code compression and minification run 100% client-side directly inside your browser. Your files remain completely private.

Rate Limits

UI Limits
100 uses per 15 minutes
Max payload size: 5 MB
API Limits
5 requests per 60 minutes
Max payload size: 256 KB
Need higher API rate limits, increased payload sizes, or custom developer solutions?
Contact our engineering team at support@blueutils.com for custom rate limit increases, higher quota allocations, or tailored enterprise integrations.