How to Minify HTML
Reduce HTML file size by removing whitespace, comments, and redundant attributes.
Problem
You need to reduce your HTML file size for faster page loads.
Prerequisites
- Understanding of HTML structure
- Knowledge of whitespace significance
Steps
-
1. Identify safe-to-remove content
Whitespace between block-level tags, HTML comments, and redundant attributes (like type='text' on script tags) can be removed. However, whitespace in <pre> tags and inline elements with display:inline may be significant.
Input<div> <p>Hello</p> </div>Outputsafe to minify -
2. Minify the HTML
Remove comments, collapse whitespace between tags, and remove optional closing tags and quotes around attribute values where safe. Preserve whitespace inside <pre>, <textarea>, and <script> content. The result is a single compact line.
Input<div>\n <p>Hello</p>\n</div>Output<div><p>Hello</p></div> -
3. Verify the page renders identically
Open the minified HTML in a browser and compare with the original. Check that inline elements still have correct spacing and that <pre> content is preserved. Automated visual regression testing can catch issues.
Inputminified HTMLOutputrenders identically
Expected result
A smaller HTML file that renders identically to the original.
Common errors
- Inline elements lose spacing
- Whitespace between inline elements (like <span>) can be significant. Use a minifier that collapses whitespace only between block-level elements, or preserve inline whitespace.
- Script or style content is corrupted
- Content inside <script> and <style> tags must not be whitespace-collapsed. Use a minifier that treats these as raw text.
Troubleshooting
- If the page looks different after minification, check <pre> and inline element whitespace.
- Conditional comments (<!--[if IE]>) should be preserved for legacy IE support.
Security limits
- Minification does not sanitize HTML. If the source has XSS vectors, they remain after minification.
Related tools
Related tasks
Ready to run it?