How do I ensure that whitespace is preserved in Markdown?

Markdown is used primarily to generate HTML, and HTML collapses white spaces by default. Use   instead of space characters.


Use non-breaking spaces

To preserve spaces in a markdown document use a non-breaking space:
"a space character that prevents consecutive whitespace characters from collapsing into a single space, and also prevents an automatic line break at its position".

Example

See an online and editable example here.

This line uses            non-breaking            spaces in many places;       they are not collapsed.
                                   There is no need to use code blocks.

This line uses many consecutive spaces in many places; they are all collapsed.

Note:
Copy and paste the previous example could not work because sometimes the non-breaking spaces are changed to normal spaces in a copy-paste operation :‑(.

Or tray a table

However, if you intend to use non-breaking spaces to align text, prefer to use tables.

Example code:

| Country  | Capital |
| -------- | --------|
| Portugal | Lisbon  |
| Spain    | Madrid  |
| Cuba     | Havana  | 

But not all Markdown implementations recognize the previous syntax.

How to introduce a non-breaking space?

  • In macOS, you need to press ⌥ Opt+Space
  • In Windows, sometimes work Alt+0+1+6+0 or Alt+2+5+5
  • In many commercial software Ctrl+Space
  • In Linux, Compose key enabled Compose Space Space

The beauty of this solution is that you don't need to use any code in your Markdown document. For example, in HTML you must use  .

PS:
Reader, please, let us know in the comments is this method does not work in your particular markdown editor. I have tested this method in two apps and several online editors.

Tags:

Markdown