There is a difference between what is written in your HTML code, and what is displayed in the browser.
As we’ve already seen, HTML tags like
<p> are only read by the browser (to know what kind of content is written), but are not displayed by the browser.
We’ve also seen how it’s possible to write HTML comments in your code, to help the human reading the code, without having these comments being displayed by the browser.
Another kind of written code ignored by the browser is whitespace, which includes:
tabulations (or indentation)
Line-breaks and empty lines (which are a succession of line-breaks) in HTML code are ignored by the browser. They only account for a single space.
The original idea of the web was that it should be a collaborative space where you can communicate through sharing information.
In order to actually force a line-break, you need to use the
<br> HTML element:
At its best, life is completelyunpredictable.
A tabulation is a special character obtained by pressing the “Tab” key. It usually moves the cursor to the next tab stop, but sometimes is converted to 2 spaces.
Anyway, like a regular space, a tabulation is invisible. It’s also ignored by the browser:
Let's push this text with tabulations.
If you want to add space before a word, you’ll have to use CSS, which we’ll cover in the next chapter.
If you want to close an HTML element, you first have to close all its children elements.
As HTML elements can be nested within each other, you have to keep track of the order in which they have been opened, as it will affect the order in which they are closed.
This code is written on a single line.
As it can be hard to keep track of the order in which HTML elements have been opened, it is recommended to write HTML in a tree format:
This code is written on multiple lines but will nevertheless be displayed on a single one.
The tree format allows to visually replicate the nesting levels of your HTML code. It’s thus easy to see that:
<article>is the ancestor
<p>is the parent of
Write HTML for you to read
Tabulations, empty lines, successive spaces, and line-breaks, are dismissed by the computer, and are all converted into a single space.
An HTML document is both written and read by a human, but only read by a computer. Considering tabulations, spaces and line-breaks don’t affect the way a browser will read and subsequently display your webpage, you may as well format your document in the most readable way for you.
There aren’t specific rules concerning HTML formatting, but there are implicit conventions, specifically:
use tabulations to help visualize how HTML elements are nested
put opening and closing tags of block-level elements on their own line
write inline elements on one line (including opening and closing tags)