HTML 포매팅이란 무엇인가요?
HTML 포매터는 HTML 포매팅(미화 또는 pretty-printing이라고도 함)을 수행하는 도구입니다. HTML 마크업에 일관된 들여쓰기, 줄 바꿈, 공백을 추가하여 중첩 구조를 눈에 보이게 만듭니다. 브라우저는 HTML을 렌더링할 때 공백을 무시하므로, 한 줄로 작성된 문서와 들여쓰기가 잘 된 문서는 동일한 출력을 냅니다. 차이는 전적으로 사람을 위한 것입니다. 포매팅된 HTML은 읽기, 디버깅, 유지 관리가 훨씬 쉽습니다.
HTML 명세(WHATWG의 HTML Living Standard로 관리됨)는 110개 이상의 요소를 정의하며, 각 요소에는 고유한 콘텐츠 모델이 있습니다. <div>, <section>, <article>과 같은 블록 수준 요소는 일반적으로 새 줄에서 시작하고 자식 요소를 들여씁니다. <br>, <img>, <input>과 같은 빈 요소는 닫는 태그나 들여쓸 자식이 없습니다. 좋은 포매터는 이러한 차이를 이해하고, 모든 태그 뒤에 무조건 공백을 추가하는 것이 아니라 그에 맞는 들여쓰기 규칙을 적용합니다.
포매팅은 개발 중에 가장 중요합니다. CMS 플랫폼의 출력, 브라우저 DevTools에서 복사한 마크업, 압축되거나 기계 생성된 HTML은 흔히 한 줄의 빽빽한 텍스트로 도착합니다. 들여쓰기가 없으면 누락된 닫는 태그를 찾거나 깊이 중첩된 구조를 추적하는 데 훨씬 더 많은 시간이 걸립니다. HTML 포매터는 그 텍스트 덩어리를 올바르게 들여쓰인 읽기 쉬운 트리 구조로 한 번에 변환합니다.
이 HTML 포매터를 사용하는 이유
어떤 HTML이든 붙여넣으면 즉시 올바르게 들여쓰인 결과를 얻을 수 있습니다. 플러그인 설치, 설정 파일 작성, 계정 생성이 필요 없습니다.
HTML 포매터 사용 사례
HTML 들여쓰기 규칙
HTML 포매터가 각 요소 유형을 처리하는 방법은 콘텐츠 모델에 따라 다릅니다. 아래 표는 일반적인 요소와 2칸 및 4칸 설정으로 들여쓰는 방법을 보여줍니다. 두 설정 모두 브라우저에서 동일하게 렌더링됩니다. 차이는 가독성에 있습니다.
| 태그 | 요소 유형 | 2칸 들여쓰기 | 4칸 들여쓰기 |
|---|---|---|---|
| <div> | Block element | New line, indent children | New line, indent children |
| <span> | Inline element | New line, indent children | Inline with parent text |
| <br> | Void element | New line, same level | New line, same level |
| <img> | Void element | New line, same level | New line, same level |
| <!-- --> | Comment | New line, same level | New line, same level |
| <!DOCTYPE> | Document type | First line, no indent | First line, no indent |
| <script> | Script block | New line, preserve inner | New line, preserve inner |
| <pre> | Preformatted | New line, preserve inner | New line, preserve inner |
포매터 vs. 압축기 vs. 린터
세 도구 모두 HTML을 다루지만 목적이 다릅니다. 포매팅과 압축은 서로 반대되는 변환이며, 린터는 공백을 변경하지 않고 오류를 검사합니다.
코드 예제
주요 언어와 도구에서 HTML을 프로그래밍 방식으로 포매팅하는 방법:
import { html as beautify } from 'js-beautify'
const ugly = '<div><p>Hello</p><ul><li>One</li><li>Two</li></ul></div>'
const formatted = beautify(ugly, {
indent_size: 2,
indent_char: ' ',
wrap_line_length: 80,
preserve_newlines: false,
})
// → <div>
// → <p>Hello</p>
// → <ul>
// → <li>One</li>
// → <li>Two</li>
// → </ul>
// → </div>from bs4 import BeautifulSoup ugly = '<div><p>Hello</p><ul><li>One</li><li>Two</li></ul></div>' soup = BeautifulSoup(ugly, 'html.parser') print(soup.prettify(formatter='minimal')) # → <div> # → <p> # → Hello # → </p> # → <ul> # → <li>One</li> # → <li>Two</li> # → </ul> # → </div>
package main
import (
"bytes"
"fmt"
"golang.org/x/net/html"
"strings"
)
func main() {
ugly := "<div><p>Hello</p></div>"
doc, _ := html.Parse(strings.NewReader(ugly))
var buf bytes.Buffer
html.Render(&buf, doc)
fmt.Println(buf.String())
// renders normalized HTML — pair with indent logic for pretty output
}# Format a single file in place npx prettier --write index.html # Format and print to stdout (pipe-friendly) npx prettier --parser html index.html # Format with 4-space indentation npx prettier --tab-width 4 --parser html index.html # Format HTML from stdin echo '<div><p>Hello</p></div>' | npx prettier --parser html