Self-Closing Tags

This lesson is part of the Web Programming 1 Course.

Until now, I've been telling you to think of elements as containers. But that's not true for all elements. Some elements cannot contain text or other elements. These elements consist of a single opening tag (instead of a pair of tags).

Here's an example of a self-closing tag:

<hr>

An hr element puts a line across the page (hr stands for 'horizontal rule'), and it can be used to visually separate the content into sections. Note that it doesn't make sense to put anything inside an hr element because it's just meant to be a thin line, which is why it's self-closing.

By the way, the hr tag is a great example of block-level element because you can clearly see how it stretches out to occupy as much horizontal space as it can.

In earlier versions of HTML, the syntax for writing self-closing tags required a forward slash before the angle bracket at the end

<hr />

The forward slash is no longer required, it's optional, but the nice thing about it is that it helps beginners to recognize an element as self-closing.

Another self-closing tag is the br element, which is used to add line breaks to a page. Before demonstrating the br element, it helps to see how white space in HTML code appears when the page is viewed in the browser. Consider this code:

<p>This is a              paragraph.</p>;


<p>This is another paragraph.</p>

This code looks a bit funny, but if you run it in the browser you'll see the the extra white space, and the empty lines do not show up on the page. White space, including line breaks and extra spaces in between words are ignored in the browser. So if you want to force a line break to occur, you can use the br element (we'll talk about forcing spaces to appear later).

<p>This is a paragraph.</p>
<br>
<br>
<p>This is another paragraph.</p>

In the code sample above, two br elements have been placed in between the paragraphs, which will force two line breaks to appear when the page is viewed in the browser.

It makes sense for a br element to be self-closing. Remember that self-closing tags cannot act as containers. It doesn't make sense for it to act as a container because it's basically just dead space.

Self-closing tags are also called void or empty tags. I'll just refer to them as 'self-closing'.

As a beginner, you may not know which tags are self-closing and which ones are not, but Sublime Text can help you with this because you just enter the tag name and press tab and it takes care of the rest. If the element is self-closing, then Sublime Text will not insert a closing tag for it.

Questions

  1. What is a self-closing tag/element?
  2. Why does a self-closing tag/element consist of just an opening tag (with no closing tag)?
  3. What are other terms used for self-closing elements?
  4. Give two examples of self-closing elements.