Lesson Monday

When you are writing HTML (or any other programming language), well-written code follows consistent indentation and spacing patterns. In some languages, indentation and spacing are required for the code to function properly. In HTML, inconsistent indentation and spacing will not impact the functionality of the web page but will cause your code to be difficult to read and understand. Sloppy code is difficult for everyone to work with.

Here is an example of some HTML with poor indentation and spacing:

<!DOCTYPE html>
<html><head>
    <title>  Example title</title>
        </head>
<body>
    <h1>Example header</h1>
  <p>  Page content  </p>
         </body>
  </html>

It is difficult to see where the various elements begin and end and which elements are nested within other elements.

Here is the same code with standard indentation and spacing:

<!DOCTYPE html>
<html>
  <head>
    <title>Example title</title>
  </head>
  <body>
    <h1>Example header</h1>

    <p>Page content</p>
  </body>
</html>

In HTML, the beginning and ending tags of an element on multiple lines should always be left-aligned. For example, when you see <html>, you should be able to visually scan the page straight down to find its closing tag (the same for <head> and <body>). One way to implement this is to create opening and closing tags at the same time and then add the contents.

When elements are nested within another element, they should be indented two spaces from the opening tag. For example, <head> is indented two spaces from <html> and <title> is indented two spaces from <head>.

If you use the tab key to space over, make sure it is set to two spaces. Some defaults are set to other amounts such as four spaces which leaves too much white space and is not standard practice.

Also, notice that there is no space between the text content of an element and its tags. For example, <h1>Example header</h1> has no spaces between <h1> and the word Example.

Regardless of the language you use to write code, learn the indentation and spacing standards for it. Practice consistency so that your code is easily readable to other developers as well as your future self.

Summary


  • In HTML, the beginning and ending tags of an element on multiple lines should always be left-aligned. For example, when you see <html>, you should be able to visually scan the page straight down to find its closing tag (the same for <head> and <body>). One way to implement this is to create opening and closing tags at the same time and then add the contents.

  • When elements are nested within another element, they should be indented two spaces from the opening tag. For example, <head> is indented two spaces from <html> and <title> is indented two spaces from <head>.