Eskillsfy

Home / Blog / Data and formats

Data and formats · 23 Nov 2026

HTML Beautifier & Minifier: how it works and how to build one

Indent minified HTML or minify it for production. This guide explains what happens behind the button and shows the code, so you can build your own.

What it does

Beautify puts every element on its own line with proper indentation, which helps when reading minified pages or email templates. Minify removes comments and whitespace between tags. Script, style and pre blocks are kept as they are.

When to use it

  • Reading minified pages
  • Cleaning up email templates
  • Tidying CMS output

How to use it

  1. Paste HTML or open a file.
  2. Choose Beautify or Minify.
  3. Copy or download the result.

Try it free in your browser, nothing is uploaded: https://eskillsfy.com/tools/html-beautifier

How it works

The beautifier splits HTML into tokens (tags, text, comments) with one regex, then prints each token on its own line with an indent that grows after an opening tag and shrinks after a closing tag.

Void elements like <img> and <br> never get a closing tag, so they don’t change the indent. Script, style and pre blocks are kept as single tokens because whitespace inside them matters.

Build it yourself

Here is the core of the tool. It has no dependencies unless noted, so you can paste it into any TypeScript or JavaScript project.

htmlBeautify.ts (ts)

const VOID = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "wbr"]);

export function beautify(html: string, pad = "  ") {
  const tokens = html.replace(/>\s+</g, "><")
    .match(/<!--[\s\S]*?-->|<(script|style|pre)\b[\s\S]*?<\/\1>|<[^>]+>|[^<]+/gi) ?? [];
  let depth = 0;
  return tokens.map((t) => {
    t = t.trim();
    if (!t) return "";
    const name = (t.match(/^<\/?([\w-]+)/)?.[1] ?? "").toLowerCase();
    if (t.startsWith("</")) return pad.repeat(--depth) + t;
    const line = pad.repeat(depth) + t;
    if (t.startsWith("<") && !t.startsWith("<!") && !VOID.has(name) && !t.endsWith("/>") && !/^<(script|style|pre)/i.test(t)) depth++;
    return line;
  }).filter(Boolean).join("\n");
}

Make it production-ready

  • Join short elements like <li>Text</li> back onto one line.
  • Add a minify mode: drop comments and whitespace between tags.

Questions

Will minifying break my page?

It removes whitespace between tags, which can join inline elements like two links. Check the page after minifying.

Try the HTML Beautifier & Minifier

Free, runs in your browser, nothing is uploaded.

Open it