Skip to content
Laviyx Learn

Try

HTML course menu

Whitespace in HTML: How Spaces and Line Breaks Are Displayed

Learn how browsers collapse spaces, tabs and new lines in HTML, how to add line breaks with br, keep formatting with pre, add non-breaking spaces with  , and why you should use CSS for spacing.

Beginner4 min readUpdated
On this page

One of the first surprises in HTML is that pressing Enter or adding extra spaces in your file does not change what the browser shows. This lesson explains why and what to use instead.

Whitespace collapses#

In normal text, the browser treats any run of spaces, tabs and new lines as a single space:

HTML
<p>This     sentence
   is spread over
         several lines.</p>
Result

The result is one line of text with single spaces. This is called whitespace collapsing. It is useful: you can indent and wrap your HTML for readability without changing the page.

Whitespace at the very start and end of a paragraph is ignored too.

Line breaks with br#

To break a line inside the same paragraph, such as in an address or a poem, use <br>:

HTML
<p>
  Laviyx Learn<br>
  12 Example Road<br>
  Hyderabad
</p>
Result

Use <br> only where the line break is part of the content. To separate ideas, use separate <p> elements, and to add space between elements, use CSS margin. Stacking <br><br><br> for spacing is a common beginner habit that is hard to maintain.

Keeping formatting with pre#

The <pre> (preformatted text) element shows text exactly as written, with all spaces and new lines, in a monospace font:

HTML
<pre>
Name      Score
Asha        92
Ravi        87
</pre>
Result

<pre> is ideal for code samples, ASCII art and text where alignment matters. A single new line straight after the opening <pre> tag is ignored, so you can start the content on the next line.

Non-breaking spaces#

&nbsp; is a non-breaking space. It does not collapse, and the browser will not wrap a line at it. Use it to keep things together, such as a number and its unit:

HTML
<p>The parcel weighs 5&nbsp;kg and costs ₹&nbsp;450.</p>
Result

Do not use rows of &nbsp;&nbsp;&nbsp; to indent text or create space; that is CSS's job.

Spaces between inline elements#

Whitespace between inline elements, such as links or images on the same line, becomes a visible space:

HTML
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Contact</a>
Result

The new lines between the links turn into the spaces you see between them. This matters later when you lay out navigation menus with CSS.

Practice#

Practice exercise

Write the first two lines of a short poem inside one paragraph so that each line appears on its own line, then show this exact table of text with its alignment preserved:

Text
Day   Hours
Mon     2
Tue     3
Show solution
HTML
<p>
  Twinkle, twinkle, little star,<br>
  How I wonder what you are.
</p>
<pre>
Day   Hours
Mon     2
Tue     3
</pre>
Result

Key takeaway#

Finished this lesson?