• google plus

How to Work with Whitespace in HTML

In computer languages, whitespace characters are those characters that create horizontal or vertical space. In this how-to you'll learn how to use whitespace in HTML documents.

  1. Create a simple HTML document by copying the following and pasting it into a new text file:
    <!DOCTYPE HTML>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title></title>
    </head>
    <body>
    
    </body>
    </html>
    

  2. Type some text between <body> and </body>. For example:
    <!DOCTYPE HTML>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title></title>
    </head>
    <body>
    Here is some text.
    </body>
    </html>
    

  3. Insert some whitespace characters into the text you typed between <body> and </body>. For example:
    <!DOCTYPE HTML>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title></title>
    </head>
    <body>
    Here
    			is      some
    			text.
    </body>
    </html>
    

  4. Save the file as whitespace.html and open it in your web browser. Notice that the words in your text still appear as if they were each separated by a single space. Web browsers ignore whitespace characters inside of elements.
    Whitespace in content.

  5. Create a <pre> element between <body> and </body> and put some text with whitespace into it. The <pre> element is the exception to the rule of browsers ignoring whitespace characters. When text is within a <pre> element web browsers will display it without ignoring the whitespace characters.
    <!DOCTYPE HTML>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title></title>
    </head>
    <body>
    <pre>This 			text
    has
    pre
    around
    it.</pre>
    Here
    			is      some
    			text, without
    				pre.
    </body>
    </html>
    

  6. Save the HTML document and open it in your web browser. It will now look like this:
    Demo of whitespace characters inside a pre element
Author: Chris Minnick
Chris is a prolific author and trainer, and the CEO of WatzThis?. His published books include Writing Computer Code, JavaScript for Kids, Coding with JavaScript For Dummies, Beginning HTML5 and CSS3 For Dummies, Webkit For Dummies, CIW eCommerce Certification Bible, and New Riders' XHTML.
About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, XML, Windows, Java, Adobe, HTML5, JavaScript, Angular, and much more. Check out our complete course catalog.