Self Closing Tags¶
Most elements always need both an opening tag and a closing tag. Some elements almost never have content inside of them, so have been given the ability to be self-closing.
<br>, stands for “Line Break”, and is very useful when you want to leave an extra space in between elements.
<p>Some text</p>
<br></br>
<p>Some more text</p>
Since the <br> element won’t have any content inside it, we can shorten it with a trailing slash to this:
<p>Some text</p>
<br/>
<p>Some more text</p>
To further complicate things, the makers of HTML have decided that some tags have the magical power to self close without a trailing slash. Personally, I don’t think that this is a good idea, as it is confusing to see an opening tag without a closing tag. The following example is also a valid use of <br>
<p>Some text</p>
<br>
<p>Some more text</p>
In the case of <img>, which stands for “Image”, the content that we want to show the human is located in a separate image file. We use the “src”, short for “Source” attribute, to tell the computer where to find the image to display.
<img src=”https://google.com/image.jpg” ></img>
Since this element also has nothing inside it, we can use a trailing slash to shorten the img element:
<img src=”https://google.com/image.jpg” />
The last tag we’ll look at in this post is the comment tag. Comments are not for the computer or the user to read, they are text specifically for you or other web developers to read. Comments are used across all computer languages to help with clarity and ensure that in 6 months when you read a complex document, that it is easy to understand.
You should write comments on any part of a document where it is not extremely easy to tell what is happening.
HTML tags inside a comment will not render, so you can comment out old parts of a document for reference later, and leave notes for yourself. Comment tags look like the below in HTML:
<!--
<h4>This is the old information, and won’t be displayed</h4>
-->
<p> This is the new information here!</p>
<!-- Todo:
We should have a link in this section
-->
You should not try to find and memorise all the HTML tags. With just these basic tags, you can create HTML documents and view them in the browser. As you create more complicated pages, you will find the need to learn and use more tags. Now that you know the basic rules all tags follow, it is easy to figure out how to use new tags that you haven’t seen before.
A cool thing you can try is to right-click a page and select “view source”. This will show you the HTML of any web page, and you can often see comments and understand the structure.
Be warned, many websites use advanced HTML to minimize the document size, especially sites that are interactive or have repeated elements. Don’t be discouraged if you don’t understand most of the Facebook or LinkedIn source code, we will discuss why HTML can end up looking so insane in future posts.