Introducing spaces and new lines with character entities

Introducing spaces and new lines with character entities cover image
  1. Home
  2. HTML
  3. Introducing spaces and new lines with character entities

When displaying the web page, browsers collapse and ignore, spaces, tabs and new line characters in the HTML. You might have spent a lot of time formatting a document using spaces only to be surprised at its display in a browser. Let us check this out.

This contains          ten space characters.
A new line character has been inserted.
		And here are 2 tabs before this line.

is displayed in the browser as:

This contains ten space characters. A new line character has been inserted. And here are 2 tabs before this line.

You’ll notice that the 10 spaces, new lines and tabs that were visible in the code above are not shown by the browser, though you will find them in the source code (VIEW-SOURCE or PAGE SOURCE).

The only HTML tag that preserves such characters and this formatting is <pre> and I have used it for code display (as above), but <pre> renders the font as fixedspaced!

Web developers employ various tricks to achieve indentation and introduce spaces in their documents. They use list tags – <ol>, <ul> and <li> – or <blockquote>. This is not advisable as HTML has a special character for introducing spaces, &nbsp; (lowercase).

Placing 8 &nbsp; will display equivalent number of space characters

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;8

          8

If you’re wondering what nbsp; means; it stands for non-breaking space character. The &nbsp; is an HTML character entity. There are tons of these and you can go through them at list of character entities.

For introducing new lines, use <br> tag (or <br />, if you are using XHTML).

HTML