Beautify HTML — Format and Indent Markup
Learn how to beautify minified HTML by restoring indentation, line breaks, and readable structure. Understand formatting options for attributes, tag placement, and nested elements.
Detailed Explanation
How HTML Beautification Works
HTML beautification takes compressed or poorly formatted markup and restores a clean, indented structure. The formatter parses the HTML into a DOM tree and re-serializes it with consistent formatting rules.
Before and After
<!-- Minified input -->
<div class=container><header><nav><ul><li><a href="/">Home</a></li><li><a href="/about">About</a></li></ul></nav></header><main><h1>Title</h1><p>Content here.</p></main></div>
<!-- Beautified output -->
<div class="container">
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
</nav>
</header>
<main>
<h1>Title</h1>
<p>Content here.</p>
</main>
</div>
Formatting Decisions
HTML beautifiers make several structural choices:
- Indent size — 2 spaces, 4 spaces, or tabs per nesting level.
- Attribute formatting — All on one line, one attribute per line for elements with many attributes, or wrap at a specified column width.
- Self-closing tags — Whether to use
<img />(XHTML style) or<img>(HTML5 style). - Inline vs. block elements — Inline elements (
<a>,<span>,<strong>) stay on the same line as surrounding text; block elements (<div>,<section>,<p>) get their own lines. - Blank lines between sections — Optionally add blank lines between major sections for readability.
Handling Mixed Content
The hardest part of HTML beautification is mixed content — elements that contain both text and child elements:
<p>Read the <a href="/docs">documentation</a> for details.</p>
A good formatter keeps this on a single line because splitting it across lines would introduce unwanted whitespace in the rendered output.
Tools for HTML Beautification
- Prettier — Handles HTML, including embedded CSS and JavaScript.
- js-beautify (
html-beautify) — Configurable HTML formatter. - VS Code built-in formatter — Provides basic HTML formatting.
When to Beautify
- Debugging server-rendered HTML to understand the DOM structure
- Reviewing HTML email templates
- Cleaning up HTML from WYSIWYG editors before committing to version control
- Comparing HTML documents in diff tools (formatted HTML produces cleaner diffs)
Use Case
HTML beautification is essential when inspecting minified server-rendered pages, cleaning up messy CMS output, or preparing HTML templates for code review where readable structure helps reviewers understand nesting and identify missing closing tags.