Skip to Content

Do browsers ignore multiple spaces in HTML?

When writing HTML code, it’s common to use multiple spaces or tabs for indentation and formatting purposes. However, browsers typically ignore multiple consecutive whitespace characters and render them as a single space.

The Basics of Whitespace Collapsing

HTML removes extra whitespace as part of a process called “whitespace collapsing.” This applies to spaces, tabs, and line breaks. Here are some key things to know about how it works:

  • Multiple spaces are collapsed into a single space
  • Newlines and tabs are converted to spaces
  • Leading and trailing whitespace is removed
  • Newlines after block level elements like divs are removed

For example, the following HTML:

<p>
   This paragraph 
   has extra  
   whitespace.
</p>

Would be rendered like this:

This paragraph has extra whitespace.

The multiple spaces and newlines are collapsed into just one space between words.

When is Whitespace Preserved?

There are a few cases where whitespace collapsing does not occur in HTML:

  • Preformatted text – The
     tag preserves all whitespace and line breaks when displaying preformatted text.
  • Non-collapsible elements - Elements like <code>, <pre>, <textarea> do not collapse whitespace within them.
  • NBSPs - Non-breaking space characters (&nbsp;) are not collapsed and will display as encoded.
  • White-space CSS property - The white-space CSS property can override default whitespace handling.

For example:

<pre>
   This preformatted 
   text keeps
   whitespace. 
</pre>

Would display as:

   This preformatted   
   text keeps
   whitespace.

Why Whitespace Collapsing Occurs

There are a few key reasons why browsers need to collapse whitespace in HTML:

  • Reduces code bulk - Removing extra whitespace significantly reduces file sizes, especially for large documents.
  • Avoids unwanted whitespace in output - Collapsing whitespace prevents too much whitespace between words or other elements.
  • Normalization - Standardizes rendering across browsers.
  • Backwards compatibility - Historic behavior in early browsers.

Without whitespace collapsing, code indentation and formatting would directly affect rendering and create unintended gaps in the output. Collapsing enables source code to be formatted neatly without impacting rendering.

Basic Recommendations

Based on the whitespace collapsing behavior, here are some recommendations on working with whitespace in HTML:

  • Use indentation and extra lines liberally in your source for readability.
  • Do not rely on multiple spaces or tabs for formatting - use CSS instead.
  • Be careful adding extra whitespace in places like tables where it may have effects.
  • Use &nbsp; to add non-breaking spaces where needed.
  • Wrap preformatted text in <pre> tags.
  • Use the CSS white-space property to override default behavior where needed.

Examples of Whitespace Handling

Here are some examples showing how browsers handle whitespace in different situations:

Multiple spaces collapsed

Source:

  
<p>
   The   quick brown fox.
</p>

Output:

The quick brown fox.

Newlines removed

Source:

<p>
The
  
quick

brown 

fox.
</p>   

Output:

The quick brown fox.

Whitespace preserved in pre

Source:

<pre>
    The   quick brown fox.
</pre>

Output:

    The   quick brown fox. 

Leading whitespace removed

Source:

<p>
    
  The quick brown fox.  
</p> 

Output:

The quick brown fox.

Trailing whitespace removed

Source:

  
<p>
The quick brown fox.         
</p>

Output:

The quick brown fox.

Line break after block element removed

Source:

<div>
This is a div.
  
</div>
<p>This is a paragraph.</p>  

Output:

This is a div.

This is a paragraph.

Whitespace preserved with nbsp

Source:

<p>
The quick&nbsp;&nbsp;brown fox.
</p>

Output:

The quick brown fox.

As you can see, there are some key patterns in how browsers handle whitespace that are good to keep in mind when writing HTML.

How Other Languages Handle Whitespace

It's useful to compare how other languages handle whitespace:

  • XML - Like HTML, XML also collapses whitespace by default.
  • Markdown - Markdown renders multiple spaces between words as a single space.
  • JavaScript - Whitespace is generally inconsequential in JavaScript, though newlines affect statement termination.
  • Python - Whitespace is significant in Python. Indentation is used to denote blocks instead of braces.
  • C - Outside of string literals, whitespace is ignored in C apart from space separating tokens.

HTML's default whitespace collapsing behavior is similar to many other textual markup and programming languages. Syntax highlighting and proper indentation practices help minimize issues.

Tools for Checking Whitespace Handling

When coding HTML, there are some handy tools you can use to visualize how whitespace is handled:

  • Browser developer tools - View element inspection and formatting.
  • HTML formatter - Formats and indents code to visualize structure.
  • WC3 HTML validator - Checks for valid HTML and warns of issues.
  • Minifiers - Removes excess whitespace and newlines to reduce file size.

These tools help check that whitespace is handled appropriately and doesn't lead to unintended rendering issues on sites.

When Whitespace Can Be Problematic

While whitespace collapsing is generally helpful, there are some cases where it can lead to problems or unexpected results:

  • Code readability - Excess collapsed whitespace can make source code harder to read and maintain.
  • Tables - Extra whitespace can affect table cell alignment and appearance.
  • Text formatting - Whitespace can sometimes break up words onto separate lines unintentionally.
  • Source comparisons - Collapsing makes it hard to see changes in compared source files.
  • Troubleshooting - Issues with whitespace can be tricky to notice and debug.

So while not common, whitespace collapsing can occasionally cause headaches that require workarounds. It's helpful to keep the potential pitfalls in mind.

When You May Want to Preserve Whitespace

While whitespace collapsing is the standard behavior, there are certain situations where you may want to preserve whitespace as authored:

  • Displaying code samples - Preserve original indentation and newlines with <pre>.
  • Writing poems or addresses - Use &nbsp; to keep whitespace.
  • Formatting tables - Avoid unintended cell alignment issues.
  • Indenting content - Use non-collapsible tags or CSS to indent.
  • Supporting comparisons - Keep original formatting for diff tools.

It basically comes down to any case where you want to display whitespace precisely as written for visual formatting reasons.

Approaches for Preserving Whitespace

There are a few main approaches you can use to preserve whitespace where needed:

  • Non-collapsible HTML tags - Use <pre>, <textarea> etc. to wrap content.
  • Non-breaking spaces - Insert &nbsp; entities where you want to keep whitespace.
  • CSS white-space property - Set to pre or pre-wrap to change default handling.
  • HTML entities - Convert spaces, tabs and newlines into HTML entities.

So if you need fine-grained control, there are options to override the standard collapsing behavior at a document, element or character level.

Typical Newline Handling in HTML

Since newlines are one of the most common whitespace characters, it's worth looking a bit deeper into how they are handled in HTML:

  • Multiple newlines collapsed to a single space.
  • Newlines after block elements like divs removed.
  • Newlines preserved inside non-collapsible elements like pre.
  • Newline entities like can be used to encode newlines.
  • The CSS white-space property can alter default newline handling.

Basically, newlines are treated just like other whitespace characters. The key exceptions are using preformatted tags or entities to encode them.

Example Newline Handling

Source:

<p>
The quick

brown fox.
  
</p>

<div>A div</div>
<p>A paragraph.</p>

<pre>
The quick  

brown fox.
</pre>

Output:

The quick brown fox.

A div

A paragraph.

The quick  

brown fox.

This shows some typical newline handling scenarios.

Strategies for Managing Whitespace

Here are some tips for managing whitespace issues in HTML:

  • Use a consistent indent style throughout documents.
  • Configure editor to show invisibles like spaces, tabs, and newlines.
  • Minify HTML to remove unnecessary whitespace for production.
  • Validate markup to check for invalid whitespace usage.
  • Use HTML tidy tools to cleanup messy whitespace.
  • Add comments to explain unusual whitespace handling.

Following coding best practices and using available tools can minimize unintended consequences.

When To Pay Extra Attention To Whitespace

There are some specific areas and tasks around HTML coding where whitespace needs extra attention:

  • Code indentation - Consistent indentation helps readability.
  • Tables - Whitespace can affect cell and layout rendering.
  • Comparison - Extra whitespace can obscure change comparisons.
  • Poetry/prose - Fine formatting often requires whitespace control.
  • Design integration - Whitespace depends on CSS styling.
  • Minification - Removing whitespace can break templates.

Being mindful of whitespace handling in these situations helps avoid pitfalls.

Conclusion

While multiple spaces and newlines are collapsed in HTML, there are cases where whitespace needs to be authored and rendered precisely.

Understanding the rules of whitespace handling enables cleaner markup while also providing control mechanisms for whitespace when needed.

With proper indentation, character encoding, and element choices, both code readability and desired rendering can be achieved.