Formatting HTML

When you write your web page, you should organize your code in a way that makes it easier to read. This is called formatting. When you format your code, you'll have an easier time finding and fixing bugs.

Whitespace

Whitespace refers to any character that shows up as a blank space on the screen, such as a space, a tab, or a new line. Whitespace helps separate different parts of the document to make it easier to read. For example, in HTML code new elements are usually put on a new line, even though it doesn't make any difference in how the page is displayed.

For example, compare the code in the two boxes below.

<body>
   <h1>Here's my list</h1>
   <ol>
      <li>Item 1</li>
      <li>Item 2</li>
   </ol>
</body>
<body><h1>Here's my list</h1><ol><li>Item 1</li><li>Item 2</li></ol></body>

Both will display the same web page, but the code in the top box is much easier to read. It's best to start off new elements in a new line.

Indentation

A very common type of formatting in HTML is indentation. Indentation is the placement of text farther to the right, or left, to separate it from surrounding text. Indentation helps to convey the program's structure. In HTML, elements that are inside other elements are usually indented.

Here is an example:

   <body>
      <p>This paragraph is inside the "body" element.</p>
   </body>

Indentation can help you remember whether or not you've closed a tag, and it also makes it clear which tags are inside others.

Commenting

As your web pages get more complicated, you'll want to use comments. Comments explain the different parts of the code and what it should create. Comments can help you to debug, and will also help other people who are trying to understand your code.

<!-- this is a comment -->

Found a bug in the documentation? Let us know at documentation@code.org