How do I format HTML without breaking inline elements and whitespace?

Dark navy cover card with the title 'How do I format HTML without breaking inline elements and whitespace?' in white and a green accent bar

To format HTML whitespace without changing the page, only add line breaks and indentation between block elements such as div, p, li and section, and never next to inline elements such as span, a, b or code where they touch text. Browsers turn whitespace between inline elements into a visible space, so a formatter that "tidies" those spots can add or remove gaps. Use a whitespace-aware formatter, keep pre and textarea content untouched, and compare the rendered text afterwards.

Why whitespace around inline elements changes the page

Whitespace around inline elements matters because the browser lays inline content out like words in a sentence. MDN's whitespace guide says "any whitespace between adjacent inline or inline-block elements will result in spaces in the layout". A line break counts as whitespace. Depending on context, the browser either turns it into a space (U+0020) or removes it.

The browser also collapses runs of whitespace. Spaces and tabs around a line break are ignored, several line breaks become one, and a space that follows another space is dropped, even across two separate inline elements. That's why indentation inside a div full of paragraphs is harmless, and why the same indentation between two span tags is not.

The element's formatting context decides which case you're in:

  • A parent that holds only inline elements creates an inline formatting context. Lines form by text wrapping, so whitespace becomes spaces.
  • In a block formatting context, each block forms its own line, so whitespace between blocks doesn't show.

The DOM keeps every whitespace character you wrote. Collapsing happens at render time, which is why the source can look different while the page stays the same, and the other way round.

A worked example: one line break, one extra space

The Prettier 1.15 release notes use a tiny example that shows the whole problem. 1<b> 2 </b>3 renders as "1 2 3", while 1<b>2</b>3 renders as "123". The only difference is whitespace inside the b tag.

Take a price label:

<p>Price: <strong>free</strong>/forever</p>

A naive formatter that puts every tag on its own line produces this:

<p>
  Price:
  <strong>free</strong>
  /forever
</p>

Now the page reads "Price: free /forever", with a space before the slash. The line break after </strong> became a space. The line breaks inside the p at the start and end are harmless, because spaces at the start and end of a line are removed.

A whitespace-aware formatter avoids that by breaking lines inside the tag brackets instead of in the text:

<p>
  Price: <strong>free</strong
  >/forever
</p>

The > at the start of a line looks odd, but it's deliberate. The break sits inside the tag, where the browser doesn't render it.

Which line breaks are safe

A line break is safe when it sits between block elements or inside a tag, and unsafe when it sits between inline content and text. Use this table before you hand-edit or accept a formatter's output.

Where the break goes Example Changes rendering?
Between two block elements </p> then <p> No
Inside a block, before its first child <div> then text No, leading spaces are removed
Between an inline element and touching text </strong> then /forever Yes, adds a space
Between two touching inline elements </a> then <a> Yes, adds a space
Inside a tag's brackets </strong then > No
Inside pre or textarea content any re-indent Yes, shows on the page
Between inline-block items </li> then <li> Yes, a visible gap

The pre case is the strictest. Content in pre uses CSS white-space: pre, where, per MDN's white-space reference, "sequences of white space are preserved". The HTML Standard says a leading newline immediately after the pre start tag is stripped, so you can start the content on the next line.

How to format HTML whitespace safely with Prettier

Prettier handles this with one setting. The htmlWhitespaceSensitivity option, first available in v1.15.0, has three values:

  1. css (default): follows each element's default CSS display value. Whitespace around inline elements is kept as it is; block elements get reformatted freely.
  2. strict: whitespace (or the lack of it) around all tags is significant. Use this for HTML emails or templates where elements are restyled to inline.
  3. ignore: whitespace around all tags is insignificant. Prettier then formats freely and can change your spacing.

On the command line that's prettier --html-whitespace-sensitivity strict page.html. In .prettierrc, add "htmlWhitespaceSensitivity": "strict".

The css mode only knows each tag's default display. If your CSS turns a span into a block, Prettier still treats it as inline. The release notes describe magic comments such as <!-- display: block --> placed before an element to tell Prettier how to treat it.

How to configure js-beautify for inline elements

js-beautify, which many editor extensions and web formatters build on, controls this with tag lists. From the js-beautify README:

  • inline: the list of tags treated as inline. Add custom tags here if they render inline.
  • unformatted: tags that shouldn't be reformatted at all. It defaults to the inline list.
  • content_unformatted: tags whose content is left alone. It defaults to pre; add textarea and any code-sample wrappers.
  • inline_custom_elements: treats custom elements as inline; the default is true.
  • wrap-line-length: for HTML it defaults to 250 characters. Long paragraphs full of links get wrapped, and every wrap point is a chance to land between inline content.

My take: set wrap-line-length to 0 (disabled) on content-heavy pages. Long lines are ugly. They never add a stray space.

How to check the formatted HTML renders the same

The fastest check is to compare the rendered text before and after formatting. MDN notes that innerText returns the text exactly as rendered, with whitespace collapsed and trimmed. So:

  1. Open the original page, then run copy(document.body.innerText) in the dev tools console and paste it into a file.
  2. Do the same with the formatted page.
  3. Diff the two. Any added or missing space next to a link or bold word shows up as a changed line.

For a quicker visual check, paste both versions into an HTML live preview and look at the spots with links, strong, code and icons. innerText can't catch inline-block gaps, because those are layout, not text. You have to see those.

Common mistakes and fixes

Most broken formatting comes from a few repeat situations:

  • Icon and text gaps. <i class="icon"></i><span>Save</span> split over two lines gets a space. Keep them on one line, or use flexbox on the parent. MDN calls flexbox the preferred fix for gaps between inline-block items.
  • Punctuation after links. A full stop moved onto its own line after </a> gains a leading space. Keep it attached.
  • &nbsp; assumptions. Non-breaking spaces (U+00A0, &nbsp;) aren't collapsed. A formatter won't remove them, but it can add regular spaces next to them.
  • Formatting minified HTML. Minified markup often relies on removed whitespace. Beautifying it can bring spaces back where the minifier took them out, the same trade-off covered in what minified JavaScript is.

The limitation: no formatter knows your final CSS. A display: inline-flex button or a span turned into a block can flip which whitespace matters, and no setting fixes that. You still have to look at the rendered page.

If you're cleaning up generated markup, the same care applies when you display Markdown as HTML or minify JavaScript in the same build. The HTML formatter on OnlineViewer Dev runs in your browser, and its tool code makes no network requests, so you can paste private templates and still check the output in the preview.

FAQ

Why does formatting my HTML add a space between two links?

The formatter put a line break between two inline elements. Browsers turn that line break into a space, so the links that used to touch now have a gap.

Which Prettier setting stops it changing whitespace?

htmlWhitespaceSensitivity. The default, css, follows each element's CSS display value. strict treats whitespace around every tag as significant, and ignore treats it as insignificant.

Is it safe to reformat the content of a pre or textarea?

No. Content inside pre keeps its spaces and line breaks, so any re-indenting shows up on the page. js-beautify leaves pre content alone by default through content_unformatted.

How do I check that formatting didn't change the page?

Compare the rendered text before and after. innerText returns text as it renders, with whitespace collapsed, so two equal innerText values mean the visible words and spaces match.

Sources