How To Keep Space In Html

When working with HTML, you might have noticed that the spacing between words or lines does not always maintain as it was in the original text. By default, HTML ignores extra spaces and line breaks, which can lead to formatting issues. In this blog post, we will explore various techniques to keep spaces and preserve the text formatting in HTML.

1.   – Non-Breaking Space

The most straightforward approach is to use the non-breaking space character entity,  . It represents a space that does not break lines and can be used to include multiple spaces between words or elements.

For example, if you want to add three spaces between two words, you can use the following code:

        <p>Word1   Word2</p>
        

However, this method can be tedious if you need to add many non-breaking spaces, and it does not preserve line breaks.

2. <pre> tag – Preformatted Text

The <pre> tag is used to represent preformatted text, which means that the spacing and line breaks in the text will be preserved exactly as they are. This tag is commonly used for displaying code snippets or text with a specific layout.

To use the <pre> tag, simply wrap the text that you want to preserve spacing in between the opening and closing tags:

        &lt;pre&gt;
        Line 1
          Line 2 (with two extra spaces)
        Line 3
        &lt;/pre&gt;
        

3. CSS – White-space Property

Another versatile approach is to use CSS to control the white space in your HTML elements. The white-space property accepts various values that determine how the white space should be handled:

  • normal (default): Collapses white space and breaks lines as necessary
  • nowrap: Collapses white space but does not break lines
  • pre: Preserves white space and line breaks
  • pre-wrap: Preserves white space and line breaks, but also wraps the text
  • pre-line: Collapses white space but preserves line breaks

To apply the white-space property, add a style attribute to the HTML element or use an external style sheet. For example, to preserve white space and line breaks in a <p> element, you can use the following code:

        &lt;style&gt;
            .preserve-space {
                white-space: pre-wrap;
            }
        &lt;/style&gt;

        &lt;p class="preserve-space"&gt;
            Line 1
              Line 2 (with two extra spaces)
            Line 3
        &lt;/p&gt;
        

In conclusion, there are multiple ways to keep space in HTML, depending on your specific requirements. Whether you choose to use non-breaking spaces, the <pre> tag, or CSS white-space properties, you now have the tools to control the spacing and formatting of your text in HTML.