πŸ› οΈToolsShed

HTML Minifier

Remove whitespace, comments, and optional tags from HTML to reduce file size.

Frequently Asked Questions

Code Implementation

# pip install htmlmin
import htmlmin

html = """<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <!-- Page title -->
    <title>My Page</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <!-- Main content -->
    <header>
      <h1>Hello, World!</h1>
      <nav>
        <a href="/">Home</a>
        <a href="/about">About</a>
      </nav>
    </header>
    <main>
      <p>
        Welcome to my website.
        This is a paragraph with extra   whitespace.
      </p>
    </main>
  </body>
</html>"""

minified = htmlmin.minify(
    html,
    remove_comments=True,
    remove_empty_space=True,
    reduce_boolean_attributes=True,
)
print(minified)

original_size = len(html.encode("utf-8"))
minified_size = len(minified.encode("utf-8"))
print(f"Original: {original_size} bytes")
print(f"Minified: {minified_size} bytes")
print(f"Savings:  {100 - minified_size / original_size * 100:.1f}%")

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.